Bru*_*ier 21 wordpress permalinks
我正在尝试创建一个自定义永久链接结构,这将允许我完成以下操作.
我希望我的永久链接结构看起来像这样:
项目/分类/项目名称
要么
/%自定义后类型%/%自定义分类%/%-名哨%/
我已经成功地在永久链接中使用/%category%/来获得正常的,开箱即用的WP帖子,但不能用于CPT.
如何创建这样的永久链接结构会影响URL或其他页面?是否可以定义自定义永久链接结构并将其限制为单个CPT?
谢谢
Ste*_*ell 26
幸运的是,我只需为客户项目做这件事.我在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 );
Run Code Online (Sandbox Code Playgroud)
注册自定义帖子类型和分类时,请务必使用以下设置:
// 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
)
);
Run Code Online (Sandbox Code Playgroud)
当然,确保在完成后刷新重写规则.祝好运!
| 归档时间: |
|
| 查看次数: |
26553 次 |
| 最近记录: |