【发布时间】:2018-08-26 05:56:23
【问题描述】:
我正在为一个有多个年龄段的运动队开发一个网站。我创建了两种自定义帖子类型(团队和球员),并希望通过 post_id 链接到每种类型的 CPT,而不是通过帖子名称通知永久链接。
我在网上找到了一些代码来使永久链接适应 post_id,但是尽管将 post_type 传递给函数,我认为这只会适应该 cpt,但它正在适应 每个 cpt - 所以尽管选择只更改团队永久链接,它会将团队和玩家的永久链接都更改为“team/post_id”。
// Rewrite permalink structure
function teams_rewrite() {
global $wp_rewrite;
$queryarg = 'post_type=teams&p=';
$wp_rewrite->add_rewrite_tag( '%cpt_id%', '([^/]+)', $queryarg );
$wp_rewrite->add_permastruct( 'teams', '/teams/%cpt_id%/', false );
}
add_action( 'init', 'teams_rewrite' );
function teams_permalink( $post_link, $id = 0, $leavename ) {
global $wp_rewrite;
$post = &get_post( $id );
if ( is_wp_error( $post ) )
return $post;
$newlink = $wp_rewrite->get_extra_permastruct( 'teams' );
$newlink = str_replace( '%cpt_id%', $post->ID, $newlink );
$newlink = home_url( user_trailingslashit( $newlink ) );
return $newlink;
}
add_filter('post_type_link', 'teams_permalink', 1, 3);
两个 CPT 在其设置中都有自己的 $arg:
'rewrite'=> array( 'with_front' => false, 'slug' => 'players' )
'rewrite'=> array( 'with_front' => false, 'slug' => 'teams' )
更新 此外,我刚刚发现这会破坏所有永久链接,但列出的团队 CPT 除外。
【问题讨论】:
标签: wordpress url-rewriting custom-post-type