0
votes

I'm struggling with a wp_query and i need your help.

I have 3 custom fields called "Agenda_day", "Agenda_month", "Agenda_year", representing the day, month and year of an event.

I want to order the results of my query by day, then month, and finally year, ascendingly.

Here is my query :

$query_agenda = new WP_Query(
    array(
        'posts_per_page' => 8, 
        'cat' => 4, 
        'meta_query' => 
            array(
                'relation' => 'AND', 
                'day' => array('key' => 'Agenda_day', 'compare' => 'EXISTS'), 
                'month' => array('key' => 'Agenda_month', 'compare' => 'EXISTS'), 
                'year' => array('key' => 'Agenda_year', 'compare' => 'EXISTS')
            ), 
        'orderby' => array('day' => 'ASC', 'month' => 'ASC', 'year' => 'ASC')
    )
);

And this does not work ... can you explain me why and show me how to fix it ?

Thank you !

EDIT

Here is the executed query (results are returned but not well ordered)

SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts LEFT JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id) INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) INNER JOIN wp_postmeta AS mt2 ON ( wp_posts.ID = mt2.post_id ) WHERE 1=1 AND ( wp_term_relationships.term_taxonomy_id IN (4) ) AND ( wp_postmeta.meta_key = 'Agenda_jour' AND mt1.meta_key = 'Agenda_mois' AND mt2.meta_key = 'Agenda_annee' ) AND wp_posts.post_type = 'post' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private') GROUP BY wp_posts.ID ORDER BY CAST(wp_postmeta.meta_value AS CHAR) ASC, CAST(mt1.meta_value AS CHAR) ASC, CAST(mt2.meta_value AS CHAR) ASC LIMIT 0, 8

2
Hey, please try to write $query_agenda->request after above code and see if query is being properly created or not? Then run that in your database and see the result. Or if possible please add that query to your question so i can get some idea.Bhoomi
also, be more detailed. where did you add the query? how are you using it? why is it not working?Samvel Aleqsanyan
ok, i edited my post with the returned executed query. The problem is that the results are not properly ordered (i don't even know on what base they are sorted, maybe post publication date...)Matthieu Marcé

2 Answers

1
votes

https://codex.wordpress.org/Class_Reference/WP_Query https://codex.wordpress.org/Class_Reference/WP_Meta_Query

please check above both links you will get your answer and your orderby arguments which you are passing it's wrong

0
votes

Problem solved !

  • i was dealing with different formats in the custom fields : some days and months were on 1 character ("6") and others on two ("06"), so the system couldn't sort it well

  • second point is, as i'm dealing with dates, i have to reorder the "orderby" instruction from "day, month, year" to "year, month, day"