开发者

How can I use category IDs in WordPress permalinks?

I want to use something like:

http://example.com/%category_id%/%postname%/

for the permalink structure.

For example, if a post has a category with an ID of 3, then the URL for the post will be

http://example.com/3/post-name/

Does anyone know how this can be d开发者_如何转开发one? I don't mind modifying WordPress core.


This code adds the %category_id% rewrite tag, and filters post permalinks to replace them with the actual category ID (lowest if there are multiple categories). You can place this in a plugin or in your theme file.

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜