ĐỨC Đỗ
ĐỨC Đỗ

Reputation: 43

Orderby price in Advanced Custom Field(ACF) Wordpress

My problem is:

I created new columns with name price in ACF in Wordpress Admin page. In the Front-end, I want to show list product with order by price descending.

And here my code of ACF in Admin WordPress show colum price:

add_filter('manage_edit-cars_columns', 'colum_xedulich');
function colum_xedulich($columns) {
    $columns = array(
            'cb' => $columns['cb'],
            'title'=>$columns['title'],
            'price_car' => __('price',_NP_TEXT_DOMAIN),
            'date' => __('Date','_NP_TEXT_DOMAIN')
        );
        return $columns;
}

add_filter('manage_cars_posts_custom_column','listProduct',10,2);
function listProduct($columns,$post_id){
    switch ($columns){
         case 'price_car':
            echo  get_field('price_from')." VNĐ ";
         break;
    }
}

But in frontend, I want to order by price in DESC but not working: My code in front-end:

$post_page = isset($_REQUEST['post_page']) ? (int)$_REQUEST['post_page'] : $_REQUEST['post_page'];
$posts_per_page = isset($_REQUEST['posts_per_page']) ? (int)$_REQUEST['posts_per_page'] : 6;

$post_page = $post_page < 1 ? 1 : $post_page;
$posts_per_page = $posts_per_page < 1 ? 1 : $posts_per_page;

$the_query = new WP_Query(array(
    'post_type' => 'cars',
    'posts_per_page' => $posts_per_page,
    'orderby' => 'price',
    'order' => 'DESC',
    'paged' => $post_page
));

Have any method to sort price of products in my case?

Upvotes: 2

Views: 456

Answers (1)

Pankaj Verma
Pankaj Verma

Reputation: 415

Replace

$the_query = new WP_Query(array(
    'post_type' => 'cars',
    'posts_per_page' => $posts_per_page,
    'orderby' => 'price',
    'order' => 'DESC',
    'paged' => $post_page
));

with

$the_query = new WP_Query(array(
    'post_type' => 'cars',
    'posts_per_page' => $posts_per_page,
    'meta_key'      => 'price',
    'orderby' => 'meta_value_num',
    'order' => 'DESC',
    'paged' => $post_page
));

Hopes it will resolve your problem.

Upvotes: 2

Related Questions