Support

Account

Home Forums General Issues Order by custom field

Solved

Order by custom field

  • I have the following code that loads the latest 5 posts which in the category
    ‘featured’. Now I need to be able to change the order of these without changing the date.
    I thought the best way would be to add a custom field (number) to each post with a ‘Feature Number’ (feature_number). (I know it’s still a little bit of a drag because you’d have to constantly open posts and rearrange the numbers to set the order)

    I am struggling to get the posts to show in this order though. I thought I could just add the following to the $args (replacing orderby), but it does not work.

    ‘meta_key’ => ‘feature_number’, ‘orderby’ => ‘meta_value_num’,

    This is the original code that works before I started messing with it. Help? 🙂

    <?php
    	$args = array('category_name' => 'featured', 'meta_key' => 'featured_order', 'order' => 'DESC', 'orderby' => 'date', 'numberposts' => '5');
    	$postslist = get_posts($args);
    	foreach ($postslist as $post):
    		setup_postdata($post); ?>
    			<div class="featured">
    				<?php the_title(); //etc. ?>
    			</div>
    		<?php
    	endforeach; 
    	wp_reset_postdata();
    ?>
  • 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.

  • Thanks John.

    I thought about the consequences of doing it this way too, where each post would have to be edited one by one. I still thought it would be better, rather than having a separate page which is ‘disconnected’ from the posts. But after some more thought, I agree with you.
    So I set up a relationship field, set it to posts and the ‘featured’ category and the Return Format as Post ID. With the following code I got it to work (only posting this in case it is useful for someone else):

    <?php
    	$posts = get_field('feature_ordering', 109); //Page ID number
    	if( $posts ):
    		foreach( $posts as $post):
    			setup_postdata($post); ?>
    				<div class="featured">
    					<?php the_title(); //etc... ?>
    				</div>
    	<?php endforeach;
    		wp_reset_postdata();
    	endif;
    ?>

    Thanks again though for the code and for making me go with the better way 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Order by custom field’ is closed to new replies.