让WordPress自动显示仅针对特定类别的类别永久链接

Bra*_*don 0 wordpress wordpress-plugin

我搜索过,这是结果.

我正在建立一个新的wordpress网站.我希望大多数帖子在网址中没有类别,只需www.site.com/title.但是我确实希望博客文章是独立的,所以我想要www.site.com/blog/title.我还想选择在未来添加更多类似的选项,仅针对特定类别,而不是整个网站.

stackoverflow上有许多与此类似的问题,但大多数都有0个回复.任何建议都会很棒.我甚至没有运气就尝试过Advanced Permalinks.

Ari*_*nto 7

您可以通过设置>永久链接来执行此操作,并将值添加到"公共设置">"自定义结构" /blog/%postname%/.在那里,您可以从www.site.com/blog/title获取博客文章.

我无法理解第一个问题.通过:

我希望大多数帖子在网址中没有类别

你的意思是没有www.site.com/category/category-name吗?或者没有www.site.com/category/post?

编辑#1

要回答这个问题:

www.site.com/category/post是我只想要"博客"类别的博客文章,如果类别是"鞋子"我不希望URL中显示类别. -

第一:您可以设置固定链接,/%postname%/以便所有帖子都可以从该链接访问所有帖子/标题

第二:您必须过滤永久链接,以便对"博客"类别下的帖子采取不同的行为.

试试这个

add_filter( 'post_link', 'custom_permalink', 10, 2 );
function custom_permalink( $permalink, $post ) {
    // Get the categories for the post
    $categories = wp_get_post_categories( $post->ID );
    foreach ( $categories as $cat ) {
        $post_cat    = get_category( $cat );
        $post_cats[] = $post_cat->slug;
    }

    // Check if the post have 'blog' category
    // Assuming that your 'Blog' category slug is 'blog'
    // Change 'blog' to match yours
    if ( in_array( 'blog',$post_cats ) ) {
        $permalink = trailingslashit( home_url( 'blog/' . $post->post_name ) );
    }

    return $permalink;
}
Run Code Online (Sandbox Code Playgroud)

第三:你必须过滤rewrite_rules

add_filter( 'rewrite_rules_array', 'custom_rewrite_rule' );
function custom_rewrite_rule( $rules ) {
    $new_rules = array(
        'blog/([^/]+)/trackback/?$' => 'index.php?name=$matches[1]&tb=1',
        'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
        'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
        'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?name=$matches[1]&cpage=$matches[2]',
        'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?name=$matches[1]&page=$matches[2]'
    );

    $rules = $new_rules + $rules;

    return $rules;
}
Run Code Online (Sandbox Code Playgroud)

转到永久链接设置并保存设置以刷新重写规则并使更改高于活动状态

注意:在活动主题functions.php模板上添加这些功能

注意:我还没有测试过,但这是你改变永久链接的方式.我做了类似的方式来更改我的档案和搜索结果的永久链接.