Question

I've been scratching my head a lot and couldn't find a reasonable solution that would not require multiple queries.

In my case, the posts have multiple tags, but they can be divided into to "sets"

  • Platforms (e.g. Facebook, Snapchat)
  • Hashtags (e.g. cold, hot, scary)

What I need to fetch are posts that belong to given Platform (can be multiple platforms) and have one of the Hashtags.

Some examples to better explain the needed results.

  • Checked tags: Facebook, cold, hot - results are posts that have "cold" and "Facebook" or "hot" and "facebook"
  • More complicated: Facebook, Snapchat, cold, hot - results are posts that have "cold" and "Facebook", "cold" and "Snapchat", "hot" and "facebook", "hot" and "snapchat".

So basically I need all the posts for a given platform that have one of the hashtags.

I do have platforms and hashtags as separate arrays in code, so I can easily distinguish between them, but the problem is that they are all "tags" from Worpdress perspective.

Was it helpful?

Solution

This should be achievable with a taxonomy query, like this:

$query = new WP_Query(
    [
        'tax_query' => [
            'relation' => 'AND',
            [
                'taxonomy' => 'post_tag',
                'terms'    => $platforms,
                'compare'  => 'IN',
            ],
            [
                'taxonomy' => 'post_tag',
                'terms'    => $hashtags,
                'compare'  => 'IN',
            ],
        ],
    ]
);

You just need to substitute the $platforms and $hashtags variables with the appropriate arrays. If there's a single platform, rather than an array I suggest just using the ID and changing the 'IN' compare value to '=' for the first array.

In my comment I said it would be easier to query with a taxonomy, but I realised that's not true, the method would be the same as above. It would however make it easier to manage the terms.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top