Search code examples
phpsqlwordpress

How to count how many categories a post have in Wordpress?


If a post has "Banana", "Orange", and "Kiwi" as categories, how can I know that the total number of categories in this post are 3?

Thank you.


Solution

  • You can use the function get_the_category within your post loop :

    <?php
    $post = get_post();
    if ( $post ) {
        $categories = get_the_category( $post->ID );
        var_dump( $categories );
    }
    

    then $categories will contain all your categories related to this post. You only have to use count($categories) to get the number.