0

To check if at least one post in post-type products has the led term I usually do this:

$query = array('numberposts' => 1, 'post_type' => array('products'), 'television' => 'led');
$products = get_posts($query);

if ($products) {
echo 'At least one post has the term led';
} else {
echo 'No post with the term led';
}

Is there a better way?

1
  • That's the way I'd do it. Jun 21, 2013 at 1:16

1 Answer 1

0

It's OK. The only problem I can see with this solution, is that you select all post data just to check if such post exists (and posts can be long).

So I would consider using custom query in this case (it gives you number of posts with this term assigned)

function my_count_posts_with_term($taxonomy, $term_slug, $post_type) {
    $term = get_term_by( 'slug', $term_slug, $taxonomy );

    $count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$wpdb->posts}
        INNER JOIN {$wpdb->term_relationships}
            ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)
        INNER JOIN {$wpdb->term_taxonomy}
            ON ({$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id)
        WHERE {$wpdb->posts}.post_type = %s
            AND {$wpdb->term_taxonomy}.taxonomy = %s
            AND {$wpdb->term_taxonomy}.term_id = %d;", $post_type, $taxonomy, $term->term_id));
    return $count;
}

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.