WP_Query class not found

That’s because when calling a theme template directly you only have what’s included/defined in the template file, not the whole WordPress environment.

Some people attempt to fix this by adding an include of wp-header or load etc but this is incredibly damaging

When doing AJAX requests, never call a file in the theme, instead call the WP AJAX APIs.

With the WP AJAX API your file becomes a simple function in functions.php.

I strongly suggest you follow the advice of this article:

http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#js-global

e.g.
PHP:

wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) )
add_action( 'wp_ajax_nopriv_myajax-submit', 'myajax_submit' );
add_action( 'wp_ajax_myajax-submit', 'myajax_submit' );

function myajax_submit() {
    // get the submitted parameters
    $postID = $_POST['postID'];

    // generate the response
    $response = json_encode( array( 'success' => true ) );

    // response output
    header( "Content-Type: application/json" );
    echo $response;

    // IMPORTANT: don't forget to "exit"
    exit;
}

JS:

jQuery.post(
    // see tip #1 for how we declare global javascript variables
    MyAjax.ajaxurl,
    {
        // here we declare the parameters to send along with the request
        // this means the following action hooks will be fired:
        // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit
        action : 'myajax-submit',

        // other parameters can be added along with "action"
        postID : MyAjax.postID
    },
    function( response ) {
        alert( response );
    }
);

Leave a Comment