Display results of one meta key and order by a dif

2019-09-17 00:21发布

On a used car dealership website, I have a PHP Query that displays all results for the relevant vehicle model. So if you visit the "Honda Civic" page it will display all the vehicles listed as a Civic.

Currently, I'm using the following query:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$args = array(
  'post_type' => array('vehicle'), 
  'post_status' => 'publish', 
  'orderby' => 'date',
  'order' => 'ASC',  
  'posts_per_page' => 10, 
  'paged' => $paged,
  'meta_key' => 'model',
  'meta_value' => $model,
);

This works as expected, however I would like to sort the result so that it displays used vehicles first and demo vehicles second. So I need to order the results by the "Demo" meta key, while still displaying only the relevant models.

I've tired the query below based on another StackOverflow question's answer, but it returns no results:

$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$args = array(
  'post_type' => array('vehicle'),
  'post_status' => 'publish',   
  'meta_key' => 'Demo', 
  'orderby' => 'meta_value',
  'order' => 'ASC',
  'posts_per_page' => 10,
  'paged' => $paged,
  'meta_query' => array(
  array('key' => 'model', 'value' => '$model')
  )
);

Any help would be appreciated.

Thanks in advance
Willem

1条回答
欢心
2楼-- · 2019-09-17 00:45

use below query argument for meta key and value.

<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1; 
$args = array(
  'post_type' => array('vehicle'),
  'post_status' => 'publish',   
  'posts_per_page' => 10,
  'paged' => $paged,
  'meta_query' => array(
                        'relation' => 'AND',
                        array(
                                'key' => 'model',
                                'value' => $model,
                                'compare' => '='
                        ),
                    ),
    'meta_key' => 'Demo',
    'orderby' => 'meta_value', //meta_value_num or meta_value
    'order' => 'ASC'

);
?>
查看更多
登录 后发表回答