WordPress have_posts()在Functions.php中不起作用 [英] WordPress have_posts() not working inside Functions.php

查看:98
本文介绍了WordPress have_posts()在Functions.php中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取消二十三个WordPress模板,并且在functions.php中有一个功能

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?

推荐答案

那是因为您必须在该函数中进行自己的查询,Ajax并不知道您当前的循环.而且最好使用 get_posts(),请参见何时应使用WP_Query与query_posts()与get_posts()?

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

会是这样的:

$my_query = get_posts( $arguments );
if( $my_query ) {
    foreach( $my_query as $p ) {
        echo $p->ID . $p->post_title;
    }
}

这篇关于WordPress have_posts()在Functions.php中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆