0

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()?

  • Are you sure that wp_ajax_wp_ajax_posts is a good name? I find that highly confusing and would suggest to avoid such. – kaiser Oct 12 '14 at 13:29
1

An ajax request happens in completely separate load, it will have no awareness about which page you are making request from and will have no main query or query conditionals.

If you want to retrieve something based on the context of page you are making request from then you need to pass that information in your ajax request and retrieve posts based on it.

  • do you know how would I pass any information from second code to script?, since echo json_encode($result); will be useless in the first function. – Murhaf Sousli Oct 12 '14 at 13:26
  • 1
    You are already passing data via localize object, you just need to add more of what you need and make use of it in your JS. – Rarst Oct 12 '14 at 13:28

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.