最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Query custom post type by custom taxonomy (category slug)

programmeradmin4浏览0评论

I've followed several related solution. But I'm still facing the problem. I've applied the following code for my custom post query by taxonomy (category). But it's not working. I think my problem with 'terms'.

$terms = get_terms('service_cat');
$services_post = new WP_Query(array(
    'post_type'         => 'service',
    'posts_per_page'    => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'service_cat',
            'field' => 'cat1',
            'terms' => $terms
        )
    ),
));

I also tried by the following code

$services_post = new WP_Query(array(
            'post_type'         => 'service',
            'posts_per_page'    => -1,
            'category_name'     => 'cat1' 
))

I've followed several related solution. But I'm still facing the problem. I've applied the following code for my custom post query by taxonomy (category). But it's not working. I think my problem with 'terms'.

$terms = get_terms('service_cat');
$services_post = new WP_Query(array(
    'post_type'         => 'service',
    'posts_per_page'    => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'service_cat',
            'field' => 'cat1',
            'terms' => $terms
        )
    ),
));

I also tried by the following code

$services_post = new WP_Query(array(
            'post_type'         => 'service',
            'posts_per_page'    => -1,
            'category_name'     => 'cat1' 
))
Share Improve this question edited Mar 31, 2016 at 8:23 Pieter Goosen 55.4k23 gold badges116 silver badges210 bronze badges asked Mar 31, 2016 at 8:04 Md Jwel MiahMd Jwel Miah 1051 gold badge5 silver badges11 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Edited to reflect question in OP's comment.

The contents of the tax_query array are not exactly right: as you're querying by slug, the field parameter of the individual taxonomy query should be "slug".

You're currently basically querying for all service posts from all service categories (well, not even that, because get_terms returns objects, but still).

To query for a single (or more than one) specific terms from which to load posts, specify the terms in the terms array. tax_query is then parsed accordingly.

$services_post = new WP_Query( array(
    'post_type'         => 'service',
    'posts_per_page'    => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'service_cat',
            'field' => 'slug',
            'terms' => array( 'cat1' ) // Array of service categories you wish to retrieve posts from
        )
    )
) );

By the way, I am assuming you want to retrieve all posts of post type service

发布评论

评论列表(0)

  1. 暂无评论