0

I have created 3 custom taxonomies to tag my posts with. On my single.php template I am attempting to count the number of terms, using get_the_terms() for each custom taxonomy that is assigned to the post, but it is not producing the result I am expecting.

I have two custom taxonomies called "sizes" and "colors" and I am getting the number of terms from these taxonomies like this:

<?php
    $sizeCount = count(get_the_terms($post->ID, 'sizes'));
    $colorCount = count(get_the_terms($post->ID, 'colors'));

    echo $sizeCount . ' ' . $colorCount;
?>

The issue is that this always seems to return at least 1(never 0), even if the post isn't tagged with any of the terms from that taxonomy. For instance, I have a post tagged with 1 size term and 0 color terms. However, this returns 1 1 when it should be returning 1 0. If I tag it with another size, the sizeCount correctly outputs and I get 2 1.

Does anyone know why I am getting a 1 even when the post is not tagged with any terms from that taxonomy?

2

If you are trying to get the number of terms your post have, then you should use wp_get_post_terms().

$sizeCount = count(wp_get_post_terms($post->ID, 'sizes'));
$colorCount = count(wp_get_post_terms($post->ID, 'colors'));

echo $sizeCount . ' ' . $colorCount;

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.