1

I want to ajaxify TwentyThirteen WordPress template and I have a function in functions.php

function prefix_ajax_add_foobar() {
    echo("add_foobar is trigered <br/>");
    if ( have_posts() ) { echo ("have posts <br/>");
        while ( have_posts() ) {
            the_post(); echo ("the_post() <br/>");
            the_ID(); echo ("the_ID() <br/>");
        } 
    }
    die("The End");
}

But I only see those results:

add_foobar is trigered 
The End

So can you give me an idea why those functions are not working?

Irakli
  • 1,151
  • 5
  • 30
  • 55
  • Well, the only thing that would stop them working would be if `have_posts()` returns false. How is this function being called? Is there a `$wpdb` query that's active at that point? – andrewsi Oct 25 '13 at 19:33
  • I don't know, I haven't done anything, I thought wp would automatically activate it. Because this piece of code is paced in index.php file, after including the header.php, it doesn't activates db. So what you suggest? What should I do? – Irakli Oct 25 '13 at 19:45
  • Where did you get the code from? Were there instructions with it? – andrewsi Oct 25 '13 at 19:52
  • Tell us, where do you call your function `prefix_ajax_add_foobar`, or how do you use it. – Ivan Hanák Oct 25 '13 at 19:57
  • Anything else is working RIGHT, like a charm, only this function has problem – Irakli Oct 25 '13 at 20:16

2 Answers2

2

That's because you have to make your own query in that function, Ajax isn't aware of your current loop. And you'd be better using get_posts(), see When should you use WP_Query vs query_posts() vs get_posts()?

It'll be something like:

$my_query = get_posts( $arguments );
if( $my_query ) {
    foreach( $my_query as $p ) {
        echo $p->ID . $p->post_title;
    }
}
Community
  • 1
  • 1
brasofilo
  • 25,496
  • 15
  • 91
  • 179
  • I just updated a full WP Ajax example [here](http://stackoverflow.com/a/13614297), check the history of the post as the first version was with a theme. And now it's a plugin. – brasofilo Oct 25 '13 at 20:10
0

have_posts() will return TRUE if it has any results to loop over and FALSE otherwise. It does seem that it is currently not getting any results. Have you tried calling query_posts($args)? Call it before the have_posts() Example: query_posts( 'posts_per_page=5' ); to show your 5 latest posts

gwinh
  • 343
  • 6
  • 12