根据作者的元值获取帖子

时间:2017-03-21 作者:Gal Hadad

假设我有一个名为“meta1”的用户元字段。我想获取帖子(通过get\\u posts或类似的方式)谁是作者meta1=true。你知道我该怎么做吗?

3 个回复
SO网友:Anwer AR

使用用户元字段获取所有用户/作者。meta1 = true

$args = array(
    \'meta_key\'     => \'meta1\',
    \'meta_value\'   => \'true\',
    \'meta_compare\' => \'=\',
    \'fields\'       => \'all\',
 );
$users = get_users( $args );
存储用户id并登录到数组中authors

$authors = array();
foreach ( (array) $users as $user ) {
  authors[ $user->ID ] = $user->user_login;
}
现在,您可以在posts查询中传递作者。

$posts = query_posts( array( \'author__in\'=> array_keys( $authors ) ) );

Or

$posts = new WP_Query( array( \'author__in\' => array( array_keys( $authors ) ) );
最终代码

$args = array(
    \'meta_key\'     => \'meta1\',
    \'meta_value\'   => \'true\',
    \'meta_compare\' => \'=\',
    \'fields\'       => \'all\',
 );
$users = get_users( $args );
$authors = array();
foreach ( (array) $users as $user ) {
    $authors[ $user->ID ] = $user->user_login;
}
$query = new WP_Query( array( \'author__in\' => array( array_keys( $authors ) ) );

if ( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();

//print post contents, title etc

endwhile;
endif;
wp_reset_postdata();

SO网友:Paul \'Sparrow Hawk\' Biron

这可以通过parse_query 过滤器,如下所示:

add_action (\'parse_query\', array ($this, \'wpse_private_author_query\')) ;

function
wpse_private_author_query ($query)
{
    // get our private author query query_var   
    $private_author_query = $query->get (\'_private_author_query\') ;
    if (empty ($private_author_query)) {
        // our private author query query_var is not set, so bail without modifying $query
        return ;
        }

    $args = array (
        \'fields\' => \'ID\',
        ) ;
    $args = wp_parse_args ($args, $private_author_query) ;
    // get the ID\'s of the users that match our private author query
    $users = get_users ($args) ;

    // unset our private author query query_var
    unset ($query->query_vars[\'_private_author_query\']) ;

    // add the author IDs to the query
    $query->set (\'author__in\', $users) ;

    return ;
}
要看到这一点,我们可以:

$args = array (
    \'post_type\' => \'any\',
    \'post_status\' => \'public\',
    \'_private_author_query\' => array (
        \'meta_key\' => \'meta1\',
        \'meta_value\' => true,
        \'meta_compare\' => \'=\',
        ),
    ) ;
$posts = new WP_Query ($args) ;
Note: 以上内容比你的问题更笼统。您只请求了user\\u meta,但上面的命令将允许通过支持的任何特征进行搜索WP_User_Query::parse_query(). 例如,我们还可以:

$args = array (
    \'post_type\' => \'any\',
    \'post_status\' => \'public\',
    \'_private_author_query\' => array (
        \'role\' => \'editor\',
        ),
    ) ;
$posts = new WP_Query ($args) ;
等等。

SO网友:Netanel Perez

您可以在循环的参数中定义它,我相信它也可以用于其他WP函数

$args = array(
  \'author\' => 1 // Author\'s ID
); 

相关推荐