I’m developing a responsive WordPress theme and instead of using frameworks, I’ve created one my own.

I’m trying NOT to repeat myself (meaning, I don’t want to write extra markup all the time), so I’m generating the HTML that comes before the .grid-unit div element with a fluid_grid PHP function that takes a function as a first parameter.

I’m pulling some custom post types using WP_Query:

function slider_template() {
    // Query Arguments
    $args = array(
        'post_type'      => 'slides',
        'posts_per_page' => 10
    );     
    // The Query
    $the_query = new WP_Query( $args );    
    // Check if the Query returns any posts
    if ( $the_query->have_posts() ) {    
        // I'm passing an anonymous function here, that needs to be called later on
        fluid_grid( function() {
            ?>    
            // Here goes the markup that should be printed out later   
            <?php
        } ); // Close the anonymous function, and end the fluid_grid function.
    } // End of the if statement
} // End of slider_template function

After visiting the page, I’m getting the following error:

Fatal error: Call to a member function have_posts() on null in ...

I’ve tried making the $the_query global, but ended up with the same result ($the_query is still null).

Is it possible to get $the_query variable working inside the anonymous function? If so, how?

2 Answers
2

This is basic PHP. Just a note before I continue, never ever globalize variables. WordPress has already done quite a crappy job regarding this. Globalization is evil, because anyone and anything, knowingly or unknowingly can change a global variable. This makes globals a nightmare to debug. So in short, NEVER EVER globalize.

Whenever you need to pass something outside a anonymous function to the function, you should use the use() keyword. As example, you can try

function () use( $the_query )
{
    var_dump( $the_query );
}

EDIT:

In your code, you can do the following

fluid_grid( function() use ( $the_query )
{
    ?>    
    // Here goes the markup that should be printed out later   
    <?php
} ); 

Leave a Reply

Your email address will not be published. Required fields are marked *