2

I'm trying to display custom post types with custom date field value being before today. It works OK for showing posts before today, but the order is only based on post date. I want to have the result ordered by meta_key.

I tried the following code and I don't understand why it doesn't work:

query_posts( array(
  'post_type'    => 'soiree',
  'orderby'      => 'meta_value',
    'meta_key'   => 'date_de_concert',
    'meta_query' => array(
        array(
           'key'            => 'date_de_concert',
           'posts_per_page' => '-1',
           'value'          => date( 'Y-m-d' ),
           'compare'        => '<',
           'type'           => 'DATE',
           'orderby'        => 'value',
           'order'          => 'DESC',
        )
    )
) );
  • I don't know if it's the problem, but meta_query should not include posts_per_page, order or orderby. It should only have key, ` value, compare, and type`. – Jacob Peattie Sep 4 '18 at 8:16
1

I prefer to use WP_Query (for more info read "When should you use WP_Query vs query_posts() vs get_posts()?"), try this way:

$args = array(
  'post_type'      => 'soiree',
  'post_status'    => 'publish',
  'posts_per_page' => -1,
  'orderby'        => 'date_de_concert',
  // you don't need 'meta_key' => 'date_de_concert' when using meta_query
  //'meta_key'     => 'date_de_concert',
  'order'          => 'DESC',
  'meta_query'     => array(
                        array(
                          'key'     => 'date_de_concert',
                          'value'   => strtotime( 'today' ),
                          'compare' => '<'
                        )
                      )
);

$concert_query = new WP_Query( $args );

if ( $concert_query->have_posts() ) : while ( $concert_query->have_posts() ) : $concert_query->the_post();
  • Thank you for your answer, but I still have the same problem. My custom posts are displayed by order based on publish date but not meta_key. Everything goes right for my first loop compared with date after today, but it doesn't work for this loop compared with date before today. If you have an idea... Thank you. – guiyom84 Sep 4 '18 at 6:58
  • @guiyom84 I modified the answer, be sure to return the correct keyname 'date_de_concert', tell me if you need more help – benny-ben Sep 4 '18 at 20:50
  • 1
    Please note: you don't need 'meta_key' => 'date_de_concert' when using meta_query. – Fayaz Sep 5 '18 at 14:01
  • @Fayaz you are right, I modified the answer – benny-ben Sep 10 '18 at 13:21

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.