【问题标题】:WordPress URL for showing post by both category and tag用于按类别和标签显示帖子的 WordPress URL
【发布时间】:2017-09-23 10:24:31
【问题描述】:

如何使用 URL 显示具有特定类别 foo 和特定标签 bar 的所有帖子?

Example: site.com/category/foo/tag/bar

或

Example: site.com/posts?category={category-id}&tag={tag-id}

【问题讨论】:

    标签: php wordpress url tags categories


    【解决方案1】:

    我不知道这是否有默认功能,但我知道如何实现它。

    您可以为此创建一个自定义模板,然后在该模板中获取 通过get_query_var() 查询字符串,然后使用 WP_Query cat 和 tag 参数来获取您属于的帖子 那只猫/标签。

    这是一个示例工作代码:

    $cat_id = get_query_var('category');
    $tag_id = get_query_var('tag');
    $args = [
        //...
        //...
        'post_type' => 'post', //<-- Replace it with your custom post_type
        'post_status' => 'publish',
        'tag_id' => $tag_id, //replace tag_id with tag if you are passing tag slug
        'cat ' => $cat_id //replace cat with category_name if your are passing category slug
        //...
        //...
    ];
    
    // The Query
    $query = new WP_Query($args);
    if (!empty($query->posts))
    {
        //print_r($query->posts);
        foreach ($query->posts as $post)
        {
            //Your filtered post
        }
    }
    

    希望这会有所帮助!

    【讨论】:

    • 只是为了澄清,因为它在 wp 中有点奇怪(当前版本是 5.7.1):get_query_var('cat') 返回 category_id,get_query_var('category_name') 返回 category_name。 get_query_var('tag') 返回 tag_name,get_query_var('tag_id') 返回 tag_id。 get_query_var('category') 不返回任何内容。
    • @honk31:我的回答是基于用户的问题,在他的 URL 中有一个名为“category”的查询参数,所以我使用了它。如果你的情况是 abc 那么你必须使用get_query_var('abc')
    • @Ranuak Gupta 确实如此。我在这里引用 wp 的内置查询变量。
    • @honk31:是的,你是对的,就是这样。 category 不是 URI 的保留字。因此,如果您的 slug 中没有它,您将一无所获。
    • 啊,现在我也明白了。哈哈。你在引用OP。我只是遇到将 2 个查询变量放在一起的问题,并且正在使用内置查询参数。通过这样做,我意识到了奇怪的 wordpress 命名,并想在这里列出它们。因为您的回答对我有帮助,我只想将这些信息添加到其中:)
    【解决方案2】:

    结构看起来像这样,但取决于您的永久链接结构。

    /category/category-name/?tag=tag-name

    【讨论】:

    • 这没有回答问题
    • 如果您选择将永久链接更改为不同于“简单”example.com/%postname% 您还应该保持英文本地化,或者您还应该更改 url 中的“类别”(例如意大利语是:example.com//**categoria**/_category-slug_/?tag=_tag-slug-1_,_tag-slug-2_)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多