Search code examples
wordpresspost-meta

Order by post_meta in wp_query wordpress not working


I want to order posts by price in wordpress, I tried a lot and also concerned by documentation, all looks good but still it is not working..

here is code....

                        global $wp_query;
                        $query_vars = $wp_query->query_vars;
                        $post_per_page = 12;
                        global $term;
                        $term = (strip_tags($_GET['term']));
                        if (!empty($_GET['term'])) {
                            add_filter('posts_where', 'taskerdev_posts_where');
                        }

                        $meta_query = array();
                        $closed = array(
                            'key' => 'closed',
                            'value' => "0",
                            'compare' => '='
                        );
                        $meta_query[] = $closed;

                        if (!empty($_GET['tasker_cat_cat']))
                            $tasker_cat = array(
                                'taxonomy' => 'tasker_cat',
                                'field' => 'slug',
                                'terms' => $_GET['tasker_cat_cat']);

                        $meta_query[] = $tasker_cat;

                        $price = array(
                                'meta_key' => 'price',
                                'orderby' => 'meta_value_num',
                                'order' => 'ASC'  
                            );
                        $meta_query[] = $price;
                        $args = array('post_type' => 'shoping',  'posts_per_page' => 10,
                            'paged' => $query_vars['paged'], 'meta_query' => $meta_query);

This code looks fine, but I cant get post order by price that is in post_meta.. I can see this code to sort results every where even in documentation of wp_query.

                                $price = array(
                                'meta_key' => 'price',
                                'orderby' => 'meta_value_num',
                                'order' => 'ASC'  
                            );
                        $meta_query[] = $price;

Solution

  • are you sure that the metafield price is numeric?

    'orderby' => 'meta_value_num',
    

    works only on numeric fields.. if a value is numeric depends on the format of price saved in your field.

    maybe post a example value so that people see what the real value is