0

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.

2
  • I would suggest making "Platforms" a separate custom taxonomy. It will make querying the posts much easier: developer.wordpress.org/plugins/taxonomies/…CommentedMay 6, 2020 at 5:30
  • Yeah, that's one of the things I was considering, but before updating over 3000 posts I was wondering if it is doable with the data I already have
    – Andy
    CommentedMay 6, 2020 at 5:35

1 Answer 1

0

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.

1
  • Just got around to test it out. Worked like a charm. Thanks a million!
    – Andy
    CommentedMay 6, 2020 at 14:58

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.