WP_Query with tax_query, order by most ‘matches’

TL;DR:
How can I sort a WP_Query based on how many ‘matches’ there are on the tax_query set. Furthermore, how can I then add more posts if the posts_per_page is not met due to the tax_query added?

Full story:
Hi all,

I’m fairly new to WP_Query editing, therefore this question. I’ve checked out multiple posts already but can’t seem to find the fitting answer.

I’m in the situation where I extend my WP_Query in the pre_get_posts hook. Here, I’m adding a tax_query to first receive posts that are in certain categories OR contain certain tags. This is (the interesting part of) the code I use in pre_get_posts:

$extend = [
    [
        'relation' => 'OR',
        [
            'taxonomy' => 'category',
            'field' => 'term_id',
            'terms' => [1, 2, 3],
            'include_children' => false
        ],
        [
            'taxonomy' => 'post_tag',
            'field' => 'term_id',
            'terms' => [6, 7, 8],
        ]
    ]
];
$query->set('tax_query', $extend);

Which actually gives me the results I want. Based on the original query, which has cat => 4, I only receive posts that have:
– Category 4, AND;
– Either category 1/2/3 OR tag 6/7/8

Which is the desired effect. However, the problem comes when the query doesn’t return enough results.

For example: The posts_per_page is set to 5 for example, and after the pre_get_posts hook the query only returns 3 posts. If this happens, I’d like to add another 2 posts to fill up to 5. These posts do not have to meet the pre_get_posts tax_query, but just the original query_vars. I’ve managed to get this working with another found_posts hook, on which I check how many posts I already have and if that’s enough to meet the posts_per_page var. If it does not, it’ll search for more posts and add those.

I’m not sure if implementing the found_posts hook is the way to go here, as I’d like to sort the posts based on how many ‘matches’ they have in the tax_query first, and then add the other posts (that do not match) to the end, so that the posts with category or tag in the tax_query get displayed first.

Has anyone else encountered this before?

Looking forward to any help, thanks a bunch!

0

Leave a Comment