我正在尝试创建一个自定义的永久链接结构,它将允许我完成以下工作。
我希望我的固定链接结构看起来像这样:
项目/类别/项目名称
或
/%custom-post-type%/%custom-taxonomy%/%post-name%/
我已经能够成功地在固定链接中为普通的、开箱即用的WP帖子使用/%category%/,但不能用于CPT。
创建这样的固定链接结构会如何影响URL或其他页面?是否可以定义自定义固定链接结构并将其限制为单个CPT?
谢谢
发布于 2014-05-17 02:45:55
你很幸运,我只是为了一个客户项目才这么做的。我使用this answer on the WordPress Stackexchange作为指南:
/**
* Tell WordPress how to interpret our project URL structure
*
* @param array $rules Existing rewrite rules
* @return array
*/
function so23698827_add_rewrite_rules( $rules ) {
$new = array();
$new['projects/([^/]+)/(.+)/?$'] = 'index.php?cpt_project=$matches[2]';
$new['projects/(.+)/?$'] = 'index.php?cpt_project_category=$matches[1]';
return array_merge( $new, $rules ); // Ensure our rules come first
}
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );
/**
* Handle the '%project_category%' URL placeholder
*
* @param str $link The link to the post
* @param WP_Post object $post The post object
* @return str
*/
function so23698827_filter_post_type_link( $link, $post ) {
if ( $post->post_type == 'cpt_project' ) {
if ( $cats = get_the_terms( $post->ID, 'cpt_project_category' ) ) {
$link = str_replace( '%project_category%', current( $cats )->slug, $link );
}
}
return $link;
}
add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );
注册自定义帖子类型和分类时,请确保使用以下设置:
// Used for registering cpt_project custom post type
$post_type_args = array(
'rewrite' => array(
'slug' => 'projects/%project_category%',
'with_front' => true
)
);
// Some of the args being passed to register_taxonomy() for 'cpt_project_category'
$taxonomy_args = array(
'rewrite' => array(
'slug' => 'projects',
'with_front' => true
)
);
当然,完成后一定要刷新重写规则。祝好运!
发布于 2021-05-12 20:36:51
由于WordPress在最近几年发生了很大的变化,因此有了一个新的解决方案。
// Used for registering cpt_project custom post type
$post_type_args = array(
'rewrite' => array(
'slug' => '/%custom-post-type%/%custom-taxonomy%/%postname%/',
'with_front' => true
'walk_dirs' => false
)
);
使用'walk_dirs‘=> false可以防止WP创建像只有^/+/这样的疯狂规则,因为您的链接以自定义post类型开始
通常,这种目录遍历甚至不是必需的,因为您只能访问结构中的站点或单独的分类站点。
这样,您的重写规则就尽可能精确了,并且您不需要使用
add_filter( 'rewrite_rules_array', 'so23698827_add_rewrite_rules' );
并在后面加上
add_filter( 'post_type_link', 'so23698827_filter_post_type_link', 10, 2 );
正如在接受的答案中所提到的。这节省了内存和执行时间!
希望这对任何人有帮助,谁正在寻找这个问题与WP版本> 5.X
https://stackoverflow.com/questions/23698827
复制相似问题