0

I can figure out this query : my purpose is to have a list of taxonomys (category like) with the number posts related to AND from today, ignoring post with a taxonomy's date before today. Something like :

Concerts (4)
Theater (10)
Cinema (12)

...

"Events" posts are store in a CPT 'event' and they all have an "event_start_date" ACF field. If I don't use the meta_query the "get_term" output well all the post by taxonomy. As soon as I try to get all posts from today's date (with the meta_query), nothing appear.

$terms = get_terms( array(
    'post_type'         => 'events',
    'hide_empty'        => false,
    'taxonomy'          => 'events_category',
    // 'orderby'        => 'name',
    // 'order'          => 'ASC',
    'meta_query' => array(
        array(
            'key'       => 'event_start_date',
            'value'     => date( "Ymd"),
            'type'      => 'date',
            'compare'   => 'LIKE',
        ),
    )
) );

I've read a lot of answers but i can't make it works, some of answers found do a ne WP-Query but I don't want post, I need a list of taxonomy (using term->count).

If anyone can guide me, I would be grateful. Thank's !

1 Answer 1

1

This is because you're using a function to get the terms, but writing the meta_query for the posts — the meta_query will actually target terms instead.

A couple of ways to solve this are:

  1. A custom SQL query
  2. Get all the posts from today, then loop through them and count up the use of each term

A custom SQL query is going to look something like this:

SELECT DISTINCT wp_terms.term_id, wp_terms.name, COUNT( wp_terms.term_id )
FROM wp_terms
JOIN wp_posts
    ON wp_posts.post_type = 'events' 
    AND wp_posts.post_status = 'publish'
JOIN wp_postmeta AS meta
    ON meta.post_id = wp_posts.id
    AND meta.meta_key = 'event_start_date'
    AND meta.meta_value = DATE_FORMAT(CURDATE(), '%Y%m%d')
JOIN wp_term_relationships AS rel
    ON rel.object_id = wp_posts.id 
WHERE rel.term_taxonomy_id = wp_terms.term_id
GROUP BY wp_terms.term_id
ORDER BY wp_terms.name ASC;

That grabs all the posts you want, with the appropriate meta key and values, then grabs the associated terms with those posts. Finally, it gets one result per term and counts up how many times that term appears.

The meta_value part could be off since I can't test that. (I just realized I also left off the specific taxonomy as well, oops. Let me know if you'd find that helpful.) If you aren't comfortable with SQL queries in WordPress, this is a good article, or you could opt for either the other solution mentioned, or one of your own devising!

1
  • Ok i'm fairly sure you're right. I find it weird not been able to do it easely. Thanks for your reply.
    – nico
    Sep 19, 2022 at 12:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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