【问题标题】:How can I use category IDs in WordPress permalinks?如何在 WordPress 永久链接中使用类别 ID?
【发布时间】:2011-09-03 19:20:13
【问题描述】:

我想使用类似的东西:

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

用于永久链接结构。
例如,如果帖子的类别 ID 为 3,则帖子的 URL 将是

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

有谁知道如何做到这一点?我不介意修改 WordPress 核心。

【问题讨论】:

  • 一般不想修改核心;它会在每次更新时中断(这意味着所有时间,现在 WP 3.7 已经发布)。使用过滤器,如下 Jan Fabry 所述。

标签: wordpress permalinks


【解决方案1】:

此代码添加 %category_id% 重写标签,并过滤帖子永久链接以将其替换为实际类别 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多