Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

This code works perfectly

function exclude_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', '-1' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

But this code does not work at all

$caid = "-1";
function exclude_category( $query ) {
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', $caid );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );
share|improve this question
    
php.net/language.variables.scope –  hakre Mar 14 '13 at 23:08

2 Answers 2

up vote 3 down vote accepted

$caid is unknown inside the function, unless declared global.

$caid = '-1';
function exclude_category( $query ) {
    global $caid;
    if ( $query->is_home() && $query->is_main_query() ) {
        $query->set( 'cat', $caid );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

// Edit
Do you need the variable outside the function at all? If not, just move it inside the function, then you can ommit the global.

PHP: Variable scope

share|improve this answer

You can as well use closures in PHP:

$catid = "-1";

$excludeCategory = function ($catid)
{
    return function ($query)
    {
        if (
            $query->is_home() 
            && $query->is_main_query()
        ) {
            $query->set('cat', $catid);
        }
    };
};

add_action('pre_get_posts', $excludeCategory($catid));

This is a function returning a function. Therefore you can pass in the catid as a parameter at the time when you register the pre_get_posts action.

share|improve this answer
    
Just out of curiosity: why would you want to do this? In the exact given case, that is. Is there some advantage using anonymous functions compared to the intuitive/'old school' way? –  t f Mar 14 '13 at 22:51
2  
in that example, the benefit is that you can inject the $catid variable at the very moment when you call add_action. That could be a benefit. When you use a global variable, the problem is that the name is defined and blocked, with this anonymous function example all you pass along is the value in form of a parameter. That's the main difference here (there are other ways to achieve the same in PHP for example with object that have the __invoke() method). –  hakre Mar 14 '13 at 23:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.