0

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' );
4

$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

2

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.

  • 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? – tfrommen 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

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.