Support

Account

Home Forums General Issues Order by custom field Reply To: Order by custom field

  • There is a way to order the results of a query by a custom field and it is explained here https://make.wordpress.org/core/2015/03/30/query-improvements-in-wp-4-2-orderby-and-meta_query/

    The problem though is that this won’t work in your case. What you want to do is first order them by the post date and then reorder the top 5 by the custom field. What you’ll need to do is sort them using PHP http://php.net/manual/en/function.usort.php

    
    <?php 
      
      // this function will be used for ordering
      // the array collected from posts by the
      // 'order' index
      function reorder_postdata_by_order($a, $b) {
        if ($a['order'] == $b['order']) {
          return 0;
        }
        return ($a['order'] < $b['order'])? -1: 1;
      }
      
      $args = array('category_name' => 'featured', 'meta_key' => 'featured_order', 'order' => 'DESC', 'orderby' => 'date', 'numberposts' => '5');
      $postslist = get_posts($args);
      $postdata = array();
      foreach ($postslist as $post):
        setup_postdata($post); 
        // collect the data you want to use for each post
        // for example the title and url
        // as well as the feature_number value
        $postdata[] = array(
          'title' => get_the_title(),
          'url' => get_permalink(),
          'order' => get_field('feature_number')
        );
        
      endforeach; 
      wp_reset_postdata();
      
      // reorder the posts
      usort($postdata);
      
      // now loop through $postdata and display list
      foreach ($postdata as $item) {
        ?>
          <div class="featured">
            <a href="<?php 
                echo $item['url']; ?>"><?php 
                echo $item['title']; ?></a>
          </div>
        <?php 
      }
      
    ?>
    

    Off the subject… if I were going to create a “Featured Posts” feature on a site I would either create a widget, or… I would use an options page with a relationship field that let the client choose the list of posts to feature and order them the way the wanted. The main reason is that by setting each post to features and editing the order on each post will require that each post must be edited. A widget or an options page would make management a lot easier because it would all be managed in one place.