WordPress theme ajax have_posts()

My goal here is to load the blogroll into my theme via ajax. But all that I can get as response is 0 (if I omit the die() line, else I get a blank response).

Here is my code:

js ajax:

$.ajax({
    url:"http://domain.com/wp-admin/admin-ajax.php",
    type:'POST',
    data:'action=load_men_blog',
    //dataType:'html',
    //cache: false,
    success: function(html){
        $("#b_contentwrapper").empty();
        $("#b_contentwrapper").append(html);
    }
});

PHP (functions.php) :

function implement_ajax() {
    while (have_posts()):
      echo "azerty";
    endwhile;
    die();
}
add_action('wp_ajax_load_men_blog', 'implement_ajax');
add_action('wp_ajax_nopriv_load_men_blog', 'implement_ajax');

Since I have posts in my database, I expect azerty to be returned. But yet I receive a blank response or 0 if I comment the die() line. If I place any echo outside the while loop I get the echo in the expected div, which means that the javascript is working.

Anyone can point me in the right direction?

2 Answers
2

The issue here is that you haven’t queried any posts. Before have_posts try adding something like, query_posts( 'posts_per_page=5' );

Leave a Comment