3

I have custom post type 'Product', and 2 custom taxonomies 'category' and 'product status'.

What i am trying to do is list categories in page template and show how many total products in category and how many of them have status 'available'

Some thing like this

Category | No. of products | Products available

Can any one show how to get posts that are in particular category and have particular status value from other taxonomy...

1 Answer 1

2

I'm sure that a custom sql query would work much better but here is an option using the WordPress Tools available

//first get all categories
$categories = get_terms( 'category', array(
    'orderby'    => 'count',
));

//then create an array for easier processing
foreach ( $categories as $cat ) {
       $slugs[] = $cat->slug;
       $counts[$cat->slug]['count'] = $cat->count;
}

//then loop over the categories and for each one create a "query" to count the number of available products
foreach($slugs as $term){
    $products = get_posts(array(
        'post_type' => 'product',
        'posts_per_page' => -1,
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => array( $term)
            ),
            array(
                'taxonomy' => 'product_status',
                'field' => 'slug',
                'terms' => array( "available"),
                'operator' => 'NOT IN',
            )
        )   
    ));
    $counts[$term]['available'] = count($products);
}

//then all the is left is to print everyting Out
if (count($counts) > 0){
    echo '<table><tr><td>Category</td><td>No. of products</td><td>Products available</td></tr>';
    foreach ($counts as $key => $val){
        echo '<tr><td>'.$key.'</td><td>'.$var['count'].'</td><td>'.$var['available'].'</td></tr>';
    }
    echo '</table>';
}
2
  • Thanks... tax_query in wp 3.xx is awsome.. well as you said custom query would work better, i printed wp_query and used as query as select count(wp_posts.id).... Jul 25, 2011 at 15:30
  • Anyone reading this, try setting posts_per_page to 1, fields to ids and use $query = WP_Query($args) instead of get_posts(); Then you can return $query->found_posts. This will be more effcient in terms of DB query and RAM used.
    – Sisir
    Apr 24 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.