即使这个问题很旧,我也会在这里提出,以防来自Google搜索的人需要更灵活的答案。
随着时间的推移,我开发了一个与WP_Query
全局查询无关的解决方案。使用custom时WP_Query
,您只能使用include
或require
能够使用上的变量$custom_query
,但是在某些情况下(对我而言,这是大多数情况!),我创建的模板部分有时会在全局查询中使用(例如封存范本)或自订WP_Query
(例如在首页查询自订文章类型)。这意味着无论查询类型如何,我都需要一个可全局访问的计数器。WordPress并未提供此功能,但是由于一些钩子,这是实现该功能的方法。
将此放置在您的functions.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;