问题描述
|
我想使用类似:
http://example.com/%category_id%/%postname%/
用于永久链接结构。
例如,如果某个帖子的类别ID为3,则该帖子的网址为
http://example.com/3/post-name/
有谁知道该怎么做?我不介意修改WordPress核心。
解决方法
此代码添加了“ 2”重写标签,并过滤了永久链接以将其替换为实际的类别ID(如果存在多个类别,则为最低)。您可以将其放置在插件或主题文件中。
add_action( \'init\',\'so6159452_init\' );
function so6159452_init()
{
add_rewrite_tag( \'%category_id%\',\'([0-9]+)\' );
}
add_filter( \'post_link\',\'so6159452_post_link\',10,2 );
function so6159452_post_link( $permalink,$post )
{
if ( false !== strpos( $permalink,\'%category_id%\' ) ) {
$cats = get_the_category( $post->ID );
if ( $cats ) {
usort( $cats,\'_usort_terms_by_ID\' ); // order by ID
$category_id = $cats[0]->cat_ID;
} else {
// Error: no category assigned to this post
// Just use a dummy variable
$category_id = \'0\';
}
$permalink = str_replace( \'%category_id%\',$category_id,$permalink );
}
return $permalink;
}