[wp-hackers] categories with no childs

The WordPress Web Warlock wordpress at web-warlocks.net
Thu May 27 15:06:21 UTC 2010


En/na capsx ha escrit:
> hi!
>
> which is the easiest way to get wordpress categories with no child 
> categories ?
>
> thx
>
Not sure if it's the easiest way, but I think this does what you asked for:

global $wpdb;
$taxonomy = 'category';
$query = "SELECT t.term_id FROM ( $wpdb->terms AS t INNER JOIN 
$wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id )" ;
$query= " WHERE ( tt.taxonomy =%s ) AND ( tt.term_id NOT IN( SELECT 
c.parent FROM wp_term_taxonomy AS c WHERE c.taxonomy=%s ) )" ;
$query = $wpdb->prepare( $query , $taxonomy  , $taxonomy );
$unfertile_parents = $wpdb->get_col( $query );

That is, get from the database all the term_ids that are categories, and 
are not parents of any term in the category taxonomy. (A term_id can, 
technically, be parent of different children in different taxonomies, 
belong to more than a taxonomy, and so checking without the first 
term_taxonomy JOIN could render wrong results. So, we must resort to the 
NOT IN(subquery) because, say, all tags are terms without children 
categories...).
Obviously, you can change the SELECT and $wpdb method to retrieve the 
full category "objects". (Just change SELECT t.term_id to, say, SELECT 
tt.*, t.*    ... and get_col to get_results. &c.)



More information about the wp-hackers mailing list