Order posts by tags count?

I am trying to order posts by tag count. I want to order posts with no tags first and posts with highest count last.

I tried and got posts with no tags only.

    $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',
    );

How do I order posts based on the tags count?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

As @Robert hue says you can’t do it directly, you need a filter and a CASE in the 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 );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x