-1

I try to order a WP_Query of a custom post type 'entry' by a meta value 'votes', but it keeps showing up ordered by date. My code:

$args = array(
        'post_type' => 'entry',
        'orderby' => 'votes',
        'order' => 'DESC',
        'posts_per_page' => 10,
        'post_status' => 'publish'
    );
$loop = new WP_Query($args);

When I evaluate $loop->request in xDebug, I get this, which indicates the results are indeed ordered by post_date DESC:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID FROM wp_posts  WHERE 1=1  AND wp_posts.post_type = 'entry' AND ((wp_posts.post_status = 'publish'))  ORDER BY wp_posts.post_date DESC LIMIT 0, 10

Do I need to use meta_query to order on custom post type meta fields? I thought that was only needed when you want to compare/restrict results based on custom meta?

2 Answers 2

4

OK, I figured it pour reading about Orderby Parameters in WP_Query more carefully. I needed to set votes to meta_key and orderby to meta_value_num:

$args = array(
        'post_type' => 'entry',
        'meta_key' => 'votes',
        'orderby' => 'meta_value_num',
        'order' => 'DESC',
        'posts_per_page' => 10,
        'post_status' => 'publish'
    );
$loop = new WP_Query($args);
1
<?php
$args = array(
  'post_type' => 'entry',
  'meta_key'       => 'start_date', //Meta field value name 
  'meta_type'      => 'DATETIME',
  'order'          => 'DESC',
  'orderby'        => 'meta_value_num',
  'posts_per_page' => 10,
  );
  $query = new WP_Query( $args );

  if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
  //Your Front End filed Value
  //Such as
  ?>
  <h4>  <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h4>
  <?php if( get_field('start_date')) { ?><strong> Start Date: </strong><?php echo the_field('start_date'); ?><?php } ?> <br>
  <?php the_excerpt(); ?> <a href="<?php the_permalink(); ?>">Read More &raquo;</a>

  <?php endwhile; endif; wp_reset_postdata(); ?>
1
  • Thanks for your answer. Although posting code is great it is good to explain why this is working.
    – Laxmana
    Mar 13, 2017 at 10:18

Your Answer

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

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