0

I want to get categories that had NO post. Below is sql for getting category with post..

SELECT terms.term_id,terms.name,COUNT(post.ID) FROM wp_posts as post
JOIN wp_term_relationships as rel ON post.ID = rel.object_ID 
JOIN wp_term_taxonomy as ttax ON rel.term_taxonomy_id = ttax.term_taxonomy_id
JOIN wp_terms as terms ON ttax.term_id = terms.term_id
WHERE ( ttax.taxonomy='category' AND post.post_type='post' AND post.post_status != 'revision') GROUP BY (terms.term_id)    

But how to get catgeory with NO post? Thank you for your help.

2 Answers 2

3

Here is how you can list the empty cat's
this way can also refrence each category data like ID, Name etc

$args = array(
    'hide_empty' => 0,
    'pad_counts' => true
);
$categories = get_categories( $args );
foreach($categories as $category) {

    if($category->count == 0) {
        echo $category->name."<br />";
    } else {
        // do nothing
    }

}
0
1

You can try this to get empty categories:

$args = array( 'hide_empty' => 1, 'hierarchical' => 0 );

add_filter( 'terms_clauses', 'custom_terms_clauses_wpse_99783' );   
$emptycats = get_terms( 'category', $args );
remove_filter( 'terms_clauses', 'custom_terms_clauses_wpse_99783' );    

where

function custom_terms_clauses_wpse_99783( $clauses ){
    $clauses['where'] = str_replace( 'tt.count > 0', 'tt.count = 0', $clauses['where'] );
    return $clauses;
}

The reason for these input arguments is to target:

    if ( $hide_empty && !$hierarchical )
            $where .= ' AND tt.count > 0';

in the function definition of get_terms, so we can do the replace.

1
  • Thank you for the answer, since in my case, script will use on theme files, i m prefer not use filter.
    – Andy
    Commented May 17, 2013 at 11:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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