我只需要数组循环中的所有作者ID,如果可能的话,每个ID只需要一次,并且在循环中的所有帖子中。有什么建议吗?
Query parsing only author ids
2 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成
假设在中有一个post对象数组$my_posts
...
$authids = array_unique(wp_list_pluck($my_posts,\'post_author\'));
您将获得当前页面帖子的作者,而不是所有帖子的作者。如果需要所有帖子的作者,您将运行另一个查询。基于中的主查询运行新查询$wp_query
...
$this_query = array_unique($wp_query->query_vars);
$this_query[\'posts_per_page\'] = -1;
$new_query = new WP_Query($this_query);
$authids = array_filter(wp_list_pluck($new_query->posts,\'post_author\'));
var_dump($authids); // debug
I caution you against this.参考号:
http://codex.wordpress.org/Function_Reference/wp_list_pluckhttp://php.net/manual/en/function.array-filter.php
SO网友:kaiser
通常情况下WP_User_Query
获取用户(/作者)。但正如我所读到的,您希望所有作者都来自当前页面循环帖子,因此可能更容易自己连接到循环中并收集它。
<?php
namespace WPSE109876;
/** Plugin Name: WPSE (#109876) Collect Author IDs */
defined( \'ABSPATH\' ) OR exit;
\\add_action( \'loop_start\', array( __NAMESPACE__.\'\\LoopCollector\', \'init\' ) )
class LoopCollector
{
public static $instance = null;
public $stack = array();
public function init()
{
is_null( self::$instance ) AND self::$instance = new self;
return self::$instance;
}
public function __construct()
{
\\add_action( \'the_post\', array( $this, \'toStack\' ) );
\\add_action( \'shutdown\', array( $this, \'printStack\' ) );
}
public function toStack( $post )
{
$aid = absint( $post->post_author );
! in_array( $aid, $this->stack )
$this->stack[] = $aid;
}
public function printStack()
{
printf( \'<hr />Author IDs<pre>%s</pre>\', join( "</br>", $this->stack ) );
}
}
结束