WordPress php function does not return value

I’m trying to write a PHP function for my WordPress theme that will return the number of categories for a given post. I’m using two files: functions.php and header.php

Contents of functions.php:

Read More
/**
*   Category count for a given post (post ID) excluding given excludecats (array).  
*   @return number
*/
function bl_cat_count($pid,$excludedcats) {
    $cat_count = 0;
    //$count = 0;
    $categories = get_the_category($pid);
    foreach($categories as $category) { 
        $cat_count++;
        if ( in_array($category->cat_ID, $excludedcats) ) {
            $cat_count--;
        } 
    }
    var_dump($cat_count);
    return $cat_count;
}

Contents of header.php:

$pid = $thumbnail->ID;
$excludedcats = array(1,85);
bl_cat_count($pid,$excludedcats);                          
var_dump($cat_count);
if ( $cat_count > 0 ) {
  // do something
}

var_dump on the function reveals the correct value. When calling from header.php however var_dump shows null. Maybe I’ve been looking at it for too long but I can’t figure out why.

Related posts

Leave a Reply

2 comments

  1. Change your header.php like this…

    $cat_count=bl_cat_count($pid,$excludedcats);                          
    var_dump($cat_count);
    

    Why it threw null ?

    That is because , you are not assigning the value returned by the bl_cat_count() to your $cat_count variable. Also , $cat_count variable’s scope is within that function i.e. bl_cat_count() !

  2. Look at this:

    $pid = $thumbnail->ID;
    $excludedcats = array(1,85);
    bl_cat_count($pid,$excludedcats);                     
    var_dump($cat_count);
    if ( $cat_count > 0 ) {
      // do something
    }
    

    So bl_cat_count is the function? And $cat_count contains the returned result of the function? So where does $cat_count get assigned?