即使这个问题很老了,我也会把它放在这里,以防来自谷歌搜索的人需要更灵活的答案。
随着时间的推移,我制定了一个解决方案WP_Query
或全局查询不可知。当您使用自定义WP_Query
, 您仅限于使用include
或require
能够使用$custom_query
, 但在某些情况下(对我来说是大多数情况!),我创建的模板部分有时用于全局查询(如存档模板)或自定义WP_Query
(如在首页上查询自定义帖子类型)。这意味着我需要一个全局可访问的计数器,无论查询类型如何。WordPress并没有提供这个功能,但这里介绍了如何通过一些挂钩实现它。
将此放在您的函数中。php
/**
* Create a globally accessible counter for all queries
* Even custom new WP_Query!
*/
// Initialize your variables
add_action(\'init\', function(){
global $cqc;
$cqc = -1;
});
// At loop start, always make sure the counter is -1
// This is because WP_Query calls "next_post" for each post,
// even for the first one, which increments by 1
// (meaning the first post is going to be 0 as expected)
add_action(\'loop_start\', function($q){
global $cqc;
$cqc = -1;
}, 100, 1);
// At each iteration of a loop, this hook is called
// We store the current instance\'s counter in our global variable
add_action(\'the_post\', function($p, $q){
global $cqc;
$cqc = $q->current_post;
}, 100, 2);
// At each end of the query, we clean up by setting the counter to
// the global query\'s counter. This allows the custom $cqc variable
// to be set correctly in the main page, post or query, even after
// having executed a custom WP_Query.
add_action( \'loop_end\', function($q){
global $wp_query, $cqc;
$cqc = $wp_query->current_post;
}, 100, 1);
此解决方案的优点在于,当您输入自定义查询并返回到常规循环时,它将以任何方式重置为正确的计数器。只要你在一个查询中(WordPress中总是这样,你几乎不知道),你的计数器就会是正确的。这是因为主查询是用同一个类执行的!
示例:
global $cqc;
while(have_posts()): the_post();
echo $cqc; // Will output 0
the_title();
$custom_query = new WP_Query(array(\'post_type\' => \'portfolio\'));
while($custom_query->have_posts()): $custom_query->the_post();
echo $cqc; // Will output 0, 1, 2, 34
the_title();
endwhile;
echo $cqc; // Will output 0 again
endwhile;