2

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:

/**
*   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.

2 Answers 2

2

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() !

Sign up to request clarification or add additional context in comments.

1 Comment

expanding upon this, the issue is the scope of the variable. If you defined that variable outside of your bl_cat_count function, then you could access it from header.php.
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.