How to fetch posts order by meta value?

2019-09-07 16:50发布

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',
    );

标签: php wordpress
3条回答
一夜七次
2楼-- · 2019-09-07 17:11

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

查看更多
小情绪 Triste *
3楼-- · 2019-09-07 17:13

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'
);
查看更多
唯我独甜
4楼-- · 2019-09-07 17:21
I hope this is solution of your problem

$args= query_posts(
    array(  'post_type' => 'your post type',
            'order'     => 'ASC',
            'meta_key' => 'some_key',
            'orderby'   => 'meta_value', //or 'meta_value_num'
            'meta_query' => array(
                                array('key' => 'order_in_archive',
                                      'value' => 'some_value'
                                )
                            )
    )
);
查看更多
登录 后发表回答