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.

  • I would suggest making "Platforms" a separate custom taxonomy. It will make querying the posts much easier: developer.wordpress.org/plugins/taxonomies/… – Jacob Peattie May 6 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 May 6 at 5:35
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.

| improve this answer | |
  • Just got around to test it out. Worked like a charm. Thanks a million! – Andy May 6 at 14:58

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.