为特定帖子类别创建自定义URL结构

时间:2018-03-08 作者:user3183717

我的自定义结构设置为“/blog/%postname%/”

这正如预期的那样工作,但对于“推荐”类别的帖子,我想将URL结构更改为“/推荐/%postname%/”。

我在我的functions.php:

//Rewrite URLs for "testimonial" category
add_filter( \'post_link\', \'custom_permalink\', 10, 3 );
function custom_permalink( $permalink, $post, $leavename ) {
    // Get the category for the post
    $category = get_the_category($post->ID);
    if (  !empty($category) && $category[0]->cat_name == "Testimonials" ) {
        $cat_name = strtolower($category[0]->cat_name);
        $permalink = trailingslashit( home_url(\'/\'. $cat_name . \'/\' . $post->post_name .\'/\' ) );
    }
    return $permalink;
}
add_action(\'generate_rewrite_rules\', \'custom_rewrite_rules\');
function custom_rewrite_rules( $wp_rewrite ) {
    $regex = \'/[\\s\\S]/\';
    $new_rules = array(
      trailingslashit(\'testimonials/\'.$regex) => \'/?p=\'. get_page_by_path(\'$matches[1]\', OBJECT, \'post\')->id
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
当我尝试单击所需的帖子时,这会生成所需的URL“myurl.com/estimationals/post name”,但随后返回404错误。

我想在不需要注册新的自定义帖子类型的情况下完成URL重写。

1 个回复
最合适的回答,由SO网友:Sally CJ 整理而成

尝试以下步骤:

Step #1: 替换此:

add_action(\'generate_rewrite_rules\', \'custom_rewrite_rules\');
function custom_rewrite_rules( $wp_rewrite ) {
    $regex = \'/[\\s\\S]/\';
    $new_rules = array(
      trailingslashit(\'testimonials/\'.$regex) => \'/?p=\'. get_page_by_path(\'$matches[1]\', OBJECT, \'post\')->id
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
    return $wp_rewrite;
}
。。使用此选项:

add_action( \'init\', \'custom_rewrite_rules\' );
function custom_rewrite_rules() {
    add_rewrite_rule(
        \'testimonials/([^/]+)(?:/([0-9]+))?/?$\',
        \'index.php?category_name=testimonials&name=$matches[1]&page=$matches[2]\',
        \'top\' // The rule position; either \'top\' or \'bottom\' (default).
    );
}
Step #2: 转到永久链接设置页面,单击保存更改按钮,而不进行任何更改。

结束

相关推荐

Functions.php中的字符串转换不起作用

我在中使用了以下代码functions.php 要翻译一些文本:add_filter(\'gettext\', \'aad_translate_words_array\'); add_filter(\'ngettext\', \'aad_translate_words_array\'); function aad_translate_words_array( $translated ) { $words = array( // \'word to