很难理解您需要在这里做什么,但您需要了解以下内容
不要将全局变量用作局部变量,这会破坏全局变量并导致循环出现问题。当您遇到问题时,也很难进行调试。唯一应该用作局部变量的全局变量是使用setup_postdata()
. setup_postdata()
需要$post
全球的您只需记住重置$post
之后为全球。
使用内部可用的操作和筛选器WP_Query
更改特定查询对象的结果
一般来说$post_count
属性是根据内部的帖子数量计算的$posts
. 在统计帖子之前the_posts
滤器这允许我们从$posts
大堆此处帖子数量的任何更改都将导致“$post\\u count”属性被更改
以下是WP_Query
班
if ( ! $q[\'suppress_filters\'] ) {
/**
* Filter the array of retrieved posts after they\'ve been fetched and
* internally processed.
*
* @since 1.5.0
*
* @param array $posts The array of retrieved posts.
* @param WP_Query &$this The WP_Query instance (passed by reference).
*/
$this->posts = apply_filters_ref_array( \'the_posts\', array( $this->posts, &$this ) );
}
// Ensure that any posts added/modified via one of the filters above are
// of the type WP_Post and are filtered.
if ( $this->posts ) {
$this->post_count = count( $this->posts );
$this->posts = array_map( \'get_post\', $this->posts );
if ( $q[\'cache_results\'] )
update_post_caches($this->posts, $post_type, $q[\'update_post_term_cache\'], $q[\'update_post_meta_cache\']);
$this->post = reset( $this->posts );
} else {
$this->post_count = 0;
$this->posts = array();
}
如果要将帖子添加到返回的帖子数组中,可以在此处执行此操作
add_filter( \'the_posts\', function ( $posts, \\WP_Query $q )
{
if ( !$q->is_main_query ) // Only target the main query, return if not. Add any additional conditions
return $posts;
$post_to_add = [
// Valid post properties
];
$post_to_add = array_map( \'get_post\', $post_to_add );
// Add some checks to make sure our $post_to_inject is a valid.
// Add $post_to_add in front of $posts array
$posts = array_merge( $post_to_add, $posts );
// If you need to replace $posts with your object
//$posts = [$post_to_add];
return $posts;
}, 10, 2 );
$post
从
$posts
数组,所以也没有必要去摆弄它。
至于$found_posts
您可以使用found_posts
筛选以调整找到的帖子数量
add_filter( \'found_posts\', function ( $found_posts, \\WP_Query $q )
{
if ( !$q->is_main_query ) // Only target the main query, return if not. Add any additional conditions
return $found_posts;
$found_posts = 1; // Taken info from your question
return $found_posts;
}):
正如我所说,我并不特别确定你需要做什么,但我希望我确实触及了你所追求的要点