0

How can I get a wp query that is sorted by how many tags (in my case) match a specified list? I want to retrieve a list of posts that match the category of the current post (which is a plain filter) but that are ordered from the highest number of matching tags to the lowest. Is it too much resource intensive?

0

There is no native function which to accomplish what you need. The only possible solution that I can think of is to make use of usort to sort the returned array of posts from your custom query

You will need to do the following:

  • Set you list with the desired tags

  • Get a list of the tags a post belongs to

  • Return an array with all the tags that match the two arrays

  • Count the tags, and store the tag count in an array

  • Sort your array and loop through the posts again and display as normal

The functions used here are as follows

Here is an example code. Modify as needed

$args = array(
    'posts_per_page' => '-1',
    'cat' => 'YOUR_CATID',
);
$q = new WP_Query( $args );

if( $q->have_posts() ) {
$count = [];
$count1 = [];

    while( $q->have_posts() ) {
        $q->the_post();

        $posttags = get_the_tags();
        if( $posttags ) {
            $tag_slugs = wp_list_pluck( $posttags, 'slug' );
            $relevant_tags = array('tag1', 'tag2', 'etc which translates to end of thought capacity' );
            $matched_tags = array_intersect( $tag_slugs, $relevant_tags );
            $count[$post->ID] = count( $matched_tags );
        }else{
            $count[$post->ID] = 0;
        }
    }

    usort( $q->posts, function ($a, $b) use($count) {

        return ($count[$a->ID] < $count[$b->ID]) ? 1 : -1;

    });

    rewind_posts();

    while( $q->have_posts() ) {
        $q->the_post();

        //Display your loop elements

    }
}
  • I am sorry for not replying, I ended up using the code found here: wordpress.org/support/topic/…, maybe slow on performance to a degree but does not seem that bad to me, also I am still not heavy caching, I also made this compatible network wide with a few modification and an external plugin. I do not quite remember why I did not use the code suggested here, the code uses usort the same – untore Dec 29 '14 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.