在 Wordpress 的后端,我使用默认的 http://localhost/sitename/example-post/
创建永久链接的值(value)。
对于自定义帖子类型,我以这种方式定义了自定义 slug,这里是 services
例如:
register_post_type( 'service',
array(
'labels' => array(
'name' => __( 'Services' ),
'singular_name' => __( 'Service' )
),
'public' => true,
'has_archive' => true,
'rewrite' => array(
'slug' => 'services',
'with_front' => true
),
'supports' => array(
'title',
'editor',
'excerpt',
'thumbnail'
),
'taxonomies' => array( 'category' ),
)
);
它创建 服务/职位名称 .
我还使用这个钩子(Hook)来创建一个自定义页面来创建一个自定义页面永久链接:
function custom_base_rules() {
global $wp_rewrite;
$wp_rewrite->page_structure = $wp_rewrite->root . '/page/%pagename%/';
}
add_action( 'init', 'custom_base_rules' );
它创建 页面/帖子名称
现在我唯一需要做的就是为普通的 Wordpress 创建另一个自定义永久链接路径。帖子 .
所以结果世界是
post
的帖子类型:职位/职位名称
我不能为此使用 backed,因为我已经定义了处理永久链接的默认方式。我已经设法重写了自定义帖子类型和页面的路径......
如何改写正常的
post
以编程方式在 Wordpress 中发布类型永久链接路径?
最佳答案
您需要分两步完成。
首先使用 'with_front' => true
启用重写用于构建后注册
add_filter(
'register_post_type_args',
function ($args, $post_type) {
if ($post_type !== 'post') {
return $args;
}
$args['rewrite'] = [
'slug' => 'posts',
'with_front' => true,
];
return $args;
},
10,
2
);
这样的网址如
http://foo.example/posts/a-title
工作,但生成的链接现在是错误的。可以通过强制构建帖子的自定义永久链接结构来修复链接
add_filter(
'pre_post_link',
function ($permalink, $post) {
if ($post->post_type !== 'post') {
return $permalink;
}
return '/posts/%postname%/';
},
10,
2
);
见 https://github.com/WordPress/WordPress/blob/d46f9b4fb8fdf64e02a4a995c0c2ce9f014b9cb7/wp-includes/link-template.php#L166
关于php - 如何以编程方式更改 Wordpress 的默认帖子永久链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52427918/