How to fetch posts order by meta value?

Well I am stuck in a sorting posts in wordpress! I know this is a previously asked question, but no luck for me the codes and solutions I found here!
The below is code snippet I am using.

$args = array(
      'showposts'=>10,
      's' => $search,
      'meta_key'        => 'neighboorhood',
      'meta_value'  => $location,
      'orderby'   => 'meta_value_num',
      'meta_key'  => 'is_sort',
    );

Related posts

Leave a Reply

2 comments

  1. That can not work, since you use meta_key twice in your array. You should use an meta_query for the where clause, and meta_key only for the sort.

    $args = array(
        'showposts'=>10,
        's' => $search,
        'meta_query' => array(
    
            array(
                'key' => 'neighboorhood',
                'value' => $location
            )
        ),
        'meta_key'  => 'is_sort',
        'orderby'   => 'meta_value_num'
    );
    
  2. Just use below mentioned code to fetch posts order by meta_value :

    <?php 
    
            $myargs = array(
               'posts_per_page' => 4, //number of post to show
               's' => $search,
               'meta_key' => 'is_sort', //name of meta field
               'orderby' => 'meta_value_num', 
               'order' => 'ASC', // you can modify it as per your use
               'meta_query' => array(
                    array(
                        'key'       => 'neighboorhood',
                        'value'     => $location,
                        )
                    )
            );
    
            query_posts($myargs );
    
            if (have_posts()) : while (have_posts()) : the_post(); ?>
    
             <h2><?php the_title();?></h2>
             <p><?php the_content();?></p>
    
             <?php endwhile; 
               endif; 
               wp_reset_query();  ?>
    

    Just use the above mentioned code, you will get your desired result. If you are using this process in case of date field, then please check here for better understanding : http://www.wptricks24.com/how-to-order-wordpress-post-by-custom-field-date