Wordpress 是否向永久链接添加更多结构标记?

Wordpress 是否向永久链接添加更多结构标记?,wordpress,permalinks,Wordpress,Permalinks,我是wordpress的新手。我想知道在permalink中是否还有获取类别id的方法? 我目前的永久链接是: http:///example.com/%category%/%post_id%-%postname%.html http:///example.com/music/1-hello.html 现在我的音乐类别id为2,如何将此类别id添加到永久链接?我想说: http:///example.com/2-music/1-hello.html 您必须创建自己的永久链接结构选项卡。例如:

我是wordpress的新手。我想知道在permalink中是否还有获取类别id的方法? 我目前的永久链接是:

http:///example.com/%category%/%post_id%-%postname%.html
http:///example.com/music/1-hello.html
现在我的音乐类别id为2,如何将此类别id添加到永久链接?我想说:

http:///example.com/2-music/1-hello.html

您必须创建自己的永久链接结构选项卡。例如:

add_filter('post_link', 'cat_id_permalink', 10, 3);
add_filter('post_type_link', 'cat_id_permalink', 10, 3);

function cat_id_permalink($permalink, $post_id, $leavename) {
    if (strpos($permalink, '%catid%') === FALSE) return $permalink;

    // Get post
    $post = get_post($post_id);
    if (!$post) return $permalink;

    // Get category ID
    $category = end(get_the_category());
    $catid = $category->cat_ID;

    return str_replace('%catid%', $catid, $permalink);
}
请注意,此代码仅在帖子列在一个类别中时有效。如果文章可能被列在多个类别下,那么你必须增加一点逻辑性

此代码将添加到functions.php文件中。WordPress过滤器允许您修改或扩展核心WordPress代码的功能,而无需更改核心文件(并且有可能在下一次WordPress更新中丢失更改)

在返回已处理的url之前(通过和过滤器)调用上述代码。当函数运行时,它返回新解析的permalink结构

如果没有有效的post ID,则//Get post代码将返回原始的永久链接

//Get category ID使用Get_The_category()检索类别ID(如果存在有效的帖子ID)。注意Get_The_category()检索类别ID数组,因为帖子可能包含多个类别。end函数返回数组的最后一个元素


最后,使用str_replace,我们将%catid%选项卡与$catid变量交换,并返回新的permalink。

您能告诉我在哪里添加此代码吗?我试图添加到options-permalink.php,但似乎不起作用?将代码添加到functions.php文件中。我在上面添加了一个较长的解释:)