0

While using the WordPress Ajax API to query certain posts the content of WP_Query is always empty (that means the class exists but every property is set to null or false).

function my_ajax_admin() {
        $query = new WP_Query();
        $tab = array();


        while($query->have_posts()):
            // never reached
        endwhile;
        die(json_encode($out));
    }
}

Is it in general not possible to use WP_Query in Ajax called? May I load something into the function to make it work? Do I require additional parameters?

0

Note that the constructor of WP_Query is:

public function __construct( $query = '' ) {
    if ( ! empty( $query ) ) {
        $this->query( $query );
    }
}

so you need a non-empty query input in your current code snippet.

Here's a simple test example:

$query = new WP_Query( ['post_type' => 'post' ] );
wp_send_json_success( $query->posts );

but you can check out e.g. wp_ajax_query_attachments() to see how WordPress uses WP_Query in an ajax call.

Also check out the built-in Rest API, it might already have the query you're looking for?

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.