正如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().