WordPress have_posts() not working inside Functions.php

不羁岁月 提交于 2019-12-24 17:05:14

问题


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?


回答1:


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;
    }
}



回答2:


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



来源:https://stackoverflow.com/questions/19597850/wordpress-have-posts-not-working-inside-functions-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!