Order posts by tags count?

时间:2015-01-05 作者:user1437251

我正在尝试按标签数量订购帖子。我想先订购没有标签的帖子,最后订购计数最高的帖子。

我试过了,只得到了没有标签的帖子。

    $tags = get_tags();
    $tag_ids = wp_list_pluck( $tags, \'term_id\' );

    $args1 = array (
       \'orderby\'          => \'DEC\',
       \'post_type\'        => \'post\',
       \'pagination\'       => true,
       \'posts_per_page\'   => \'1\',
       \'tag__not_in\'      =>  $tag_ids,
       \'meta_key\'         => \'_thumbnail_id\',
    );
如何根据标签数量订购帖子?

1 个回复
最合适的回答,由SO网友:bonger 整理而成

正如@Robert hue所说,你不能直接做到这一点,你需要一个过滤器和一个CASE 在orderby eg中

$args1 = array (
   \'orderby\'          => \'tag_count\',
   \'order\'            => \'DESC\',
   \'post_type\'        => \'post\',
   \'pagination\'       => true,
   \'posts_per_page\'   => \'1\', // 1 post per page?!
   \'meta_key\'         => \'_thumbnail_id\',
   \'suppress_filters\' => false,
);

function wpse173949_posts_clauses( $pieces, $query ) {
    if ( $query->get( \'orderby\' ) != \'tag_count\' ) return $pieces;
    global $wpdb;
    if ( ! ( $order = $query->get( \'order\' ) ) ) $order = \'DESC\';
    $pieces[ \'fields\' ] .= $wpdb->prepare(
        \', (SELECT COUNT(tr.object_id) FROM \' . $wpdb->term_relationships . \' tr\'
        . \' JOIN \' . $wpdb->term_taxonomy . \' AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id\'
        . \' WHERE tr.object_id = \' . $wpdb->posts . \'.ID AND tt.taxonomy = %s) AS tag_count\'
        , \'post_tag\' );
    // Treat zero tagged posts as max int (~0).
    $pieces[ \'orderby\' ] = \'CASE WHEN tag_count THEN tag_count ELSE ~0 END \' . $order;
    return $pieces;
}

add_filter( \'posts_clauses\', \'wpse173949_posts_clauses\', 10, 2 );
$query = new WP_Query( $args1 );
remove_filter( \'posts_clauses\', \'wpse173949_posts_clauses\', 10 );

结束

相关推荐

WP_USER_Query。‘Relationship’=>‘OR’有什么问题?

我希望所有满足任一条件1的用户OR 条件2。按姓氏排序。如果我接受条件1AND 条件2(\'关系\'=>\'和\'),查询正常。如果我取“relation”=>“OR”,我会得到所有记录和未排序的记录。怎么了? $args = array( \'meta_query\' => array( \'relation\' => \'OR\', 0 => array( \'k