WordPress URL for showing post by both category and tag

谁都会走 提交于 2019-12-24 01:13:04

问题


How can I show all posts with a specific category foo and a specific tag bar by using URL?

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

or

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

回答1:


I don't know is there as default feature for the this or not but I have an idea as how to achieve it.

You can create a custom template for this and in that template get the query string by get_query_var() and then use WP_Query cat and tag argument to fetch your posts belonging to that cat/tag.

Here is a sample working code:

$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
    }
}

Hope this helps!



来源:https://stackoverflow.com/questions/43627032/wordpress-url-for-showing-post-by-both-category-and-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!