我有以下代码,虽然get\\u the\\u ID()有效,$post->ID无效,为什么?
$the_query = new WP_Query( array(
\'post_type\' => \'custompost\',
) );
while ( $the_query->have_posts() ) : $the_query->the_post();
echo $post->ID;
endwhile;
我有以下代码,虽然get\\u the\\u ID()有效,$post->ID无效,为什么?
$the_query = new WP_Query( array(
\'post_type\' => \'custompost\',
) );
while ( $the_query->have_posts() ) : $the_query->the_post();
echo $post->ID;
endwhile;
您的WP\\U查询循环不完整。在循环之前,您没有检查是否确实找到了任何帖子,也没有显示任何帖子未找到的消息,也没有在之后进行清理。您还使用了“other”语法,打破了IDE中的大括号匹配,这让您的生活更加艰难。
尝试添加global $post;
像这样:
global $post;
$the_query = new WP_Query( array(
\'post_type\' => \'custompost\'
) );
if($the_query->have_posts()){
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo $post->ID;
}
wp_reset_postdata();
}else {
echo \'no posts found\';
}
在编写查询时,保持一致性和正确处理问题很重要。因此,我建议阅读Auttomatic WordPress核心开发人员Andrew Nacin的以下幻灯片:http://www.slideshare.net/andrewnacin/you-dont-know-query-wordcamp-netherlands-2012
这将告诉您每种类型的查询适用于哪里,应该如何使用它们,以及为什么。在上面的代码中,我添加了一个if语句来检查是否返回了任何帖子,并添加了wp\\u reset\\u postdata,这将允许您通过在自定义循环之后清理来继续使用主查询。
正如Tom Nowell所指出的,诀窍在于添加对global $post
.
当你跑步时the_query->the_post()
, WordPress将查询的第一个结果加载到全局$post
对象这是它为所有常规模板标记设置的方式:
the_title()
the_content()
the_excerpt
()等$post
对象,以便分析、准备和打印所需的输出。在你的循环中,你调用the_post()
可以填充数据,但在循环范围内没有对数据本身的引用。如果要避免引用全局$post
对象,您可以使用get_the_ID()
.
就像我上面提到的其他模板标记一样,get_the_ID()
来自全球的传票数据$post
对象内部,所以您不必自己做。
但是如果您自己想这样做,只需在尝试使用之前添加一个全局引用即可$post
:
$the_query = new WP_Query( array(
\'post_type\' => \'custompost\',
) );
while ( $the_query->have_posts() ) : $the_query->the_post();
global $post; // Add this line and you\'re golden
echo $post->ID;
endwhile;
什么是wp_reset_postdata()
?如果您正在构建多个循环(即,您有一个大的post循环,但在其中调用一些辅助循环),那么您可以调用wp_reset_postdata()
重置内容。大体上the_post()
将设置全局$post
对象获取请求查询的数据。the_query->the_post()
将覆盖$post
数据来自the_query
. wp_reset_postdata()
将重置$post
到原始查询。
因此,如果使用嵌套或多个循环,wp_reset_postdata()
是一种回到循环的方式$post
调用辅助对象之前可用的对象the_query->the_post()
.
我目前正在一个杂志风格的网站上工作,在主页上,我有三个不同的部分来显示最新的新闻。滑块、最新新闻和更多新闻。问题是我不知道如何避免每个帖子上出现重复帖子。以下是查询示例:// build query query_posts( $this->getQueryParams($type, $esc_category, $this->escapeText($data[\'number_of_posts\'])) ); // loop while (have_posts()) :