I'm doing a fairly standard situation where posts are loaded with AJAX via a list. I'm having difficulty passing from WP/PHP to JS when the max posts are reached.
Here's what I use to enqueue assets in functions.php and thus, localize my script:
function news_enqueue_assets() {
global $wp_query;
wp_localize_script( 'sage_js', 'newsposts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'news_enqueue_assets', 100);
And below that, for the AJAX post loading side of things I have:
add_action( 'wp_ajax_nopriv_news_load_posts', 'news_load_posts' );
add_action( 'wp_ajax_news_load_posts', 'news_load_posts' );
function news_load_posts () {
$query_vars = json_decode( stripslashes( $_POST['query_vars'] ), true );
$query_vars = array(
'posts_per_page' => $_POST['number_of_posts'],
'paged' => $_POST['page'],
'category__and' => $_POST['category'],
'tag__in' => $_POST['tag']
);
$posts = new WP_Query( $query_vars );
$globals['wp_query'] = $posts;
if( ! $posts->have_posts() ) {
echo 'No more posts';
}
else {
while ( $posts->have_posts() ) {
$posts->the_post();
get_template_part( 'templates/news', 'single' );
echo 'Max post check: ' . $posts->found_posts;
}
}
die();
}
Lastly, the JS:
var load_posts = function() {
$.ajax({
type: 'POST',
data: {
action: 'news_load_posts',
query_vars: newsposts.query_vars,
number_of_posts : 4,
page: page,
category: category_id,
tag: get_active_tag()
},
url: newsposts.ajaxurl,
beforeSend : function(){
},
success : function(data){
$content.html(data);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
};
Everything works great, in general, I just can't figure out how to pass values TO the JS. I understand I can add other values to wp_localize_script, but then how do I pass those variables/values to function news_enqueue_assets() ?
A push in the right direction is hopefully all I need.
Thank you for your time!
news_load_posts, return a json object that contains your html plus some other var that indicates whether or not more posts exist.wp_send_json? Adding a basic array $test, and usingwp_send_json($test)in lieu of theecho 'Max post..'kills the posts output and spits out my array directly.wp_send_jsonsends the response and exit the program, so whenwp_send_jsonis executed, the code bellow it is not triggered. Also, you can not mix a JSON response with a HTML response, so it is not as simple as addingwp_send_jsonto your code; more changes are needed, both PHP and javascript, to make it work with JSON. I'm sorry but it is late here and I have not energy to post an example right now, I'll come back tomorrow.