I'm trying to ajax wp_query, I got success getting posts for home page with the following code.
Then I added conditional tags to modify the query for the other pages like Category page
the problem that all conditional tags are not working inside this function, it keeps giving me the same posts of the home page.
I'm using this code in function.php file:
add_action( 'wp_ajax_wp_ajax_posts', 'wp_ajax_posts_init' );
function wp_ajax_posts_init() {
/** Made Query */
$numPosts = (isset($_POST['numPosts'])) ? $_POST['numPosts'] : 0;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$args = array(
'posts_per_page'=> $numPosts,
'paged' => $page,
);
if(is_post_type_archive('projects')){
$args['post_type'] = 'projects';
}
if(is_category()){
$category = get_category( get_query_var( 'cat' ) );
$cat_id = $category->cat_ID;
$args['cat'] = $cat_id;
}
$theme_post_query = new WP_Query( $args );
while( $theme_post_query->have_posts() ) : $theme_post_query->the_post();
//--html content
endwhile;
wp_reset_query();
}
the weird thing that conditional tags are working in all other functions like where I enqueue the ajax script
if(is_home() || is_category() || is_search() || is_tag() || is_post_type_archive('projects')){
wp_register_script( 'ajaxLoop-js', "{$ss_url}/js/ajaxLoop.js", array('jquery'));
$php_array = array( 'admin_ajax' => admin_url( 'admin-ajax.php' ) );
wp_localize_script( 'ajaxLoop-js', 'php_array', $php_array );
wp_enqueue_script( 'ajaxLoop-js' );
}
any ideas how to get conditional tags work at wp_ajax_posts_init()
?
wp_ajax_wp_ajax_posts
is a good name? I find that highly confusing and would suggest to avoid such.