After extensive reading about this I've hit a wall with troubleshooting, so I figured I'd ask on here.
I'm building out an AJAX call that will run a WP_Query and return a series of posts that have a certain tag. The tag is specified by the user clicking on an item in a ul, which then passes the appropriate tag to the AJAX call as "data-slug".
I've built out my JS and PHP, but my AJAX call keeps returning an empty array, even though it logs a "success". I've double-checked that the correct slug is passing into the arguments for the WP_Query and that the proper scripts are enqueued. It appears the query just isn't returning anything. However, when I run the same query outside of AJAX, with the arguments hard-coded, it functions properly.
If anybody has ideas about how to proceed with this it would be much appreciated.
Here's the PHP that I've placed in functions.php:
//Enqueue custom scripts
function my_adding_scripts() {
wp_register_script('gg-load', '/wp-content/plugins/gg-load.js', array('jquery'),'1.1', true);
wp_localize_script( 'gg-load', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('gg-load');
}
add_action('wp_enqueue_scripts', 'my_adding_scripts');
//Process AJAX data
add_action( 'wp_ajax_gg_query_posts', 'gg_query_posts' );
add_action( 'wp_ajax_nopriv_gg_query_posts', 'gg_query_posts' );
function gg_query_posts() {
$response = array();
$slug = $_REQUEST["slug"];
$args = array(
'tag' => "$slug",
'orderby' => "title",
'order' => "ASC",
);
$the_query = new WP_Query ($args);
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$response->status = true;
$response->query = $the_query;
}
} else {
$response->status = false;
$response->message = esc_attr__( 'No posts were found' );
}
wp_reset_postdata();
die( json_encode( $response ) );
}
Here is the ajax call:
jQuery(document).ready( function() {
jQuery("ul.gg-menu>li").click( function(e) {
e.preventDefault();
slug = jQuery(this).attr("data-slug"); //Passes slug to the PHP script for use in the WP_Query
jQuery.ajax({
type : "post",
dataType : "json",
url : myAjax.ajaxurl,
data : {action: "gg_query_posts", slug: slug},
error: function(data) {
console.log(data, "error");
},
success: function(data) {
console.log(data, "success");
//We work with the post data here
}
})
})
})