0

I am using meta_value_num to sort posts by price and allow users to use a dropdown to change between max and min. What I need now is the ability to select from Min Price or Max Price or Newest Posted or Oldest Posted Is it possible to sort by multiple values?

WP Query

$args = array(
            'order' => $_POST['date'],
            'orderby' => 'meta_value_num date',
            'post_type' => 'product',
            'meta_key' => 'ek-product-price',
);

Form

            <select id="select1" type="text" name="date">
                <!-- FIRST 2 OPTIONS FOR SORT BY PRICE META VALUE -->
                <option value="ASC" type="hidden">ASC</option>
                <option value="DESC" type="hidden">DESC</option>
                <!-- ADD IN OPTION FOR SORT BY DATE ADDED -->
            </select>
  • You want to give options to sort by (Min Price OR Max Price OR Newest Posted OR Oldest Posted) or (Min Price AND Max Price AND Newest Posted AND Oldest Posted)? – Annapurna Sep 25 '17 at 11:20
  • @Annapurna all OR so either sort by min OR max price OR new OR oldest dates. – scopeak Sep 25 '17 at 15:18
  • why not do the same thing you're already doing with the order parameter? add another form field to choose what to order by. – Milo Sep 25 '17 at 16:32
  • @Milo id rather keep it to the same select field for ease of use, good idea though! – scopeak Sep 25 '17 at 16:43
  • I'm not sure what you're asking then. How does one select what to order by? – Milo Sep 25 '17 at 16:44
0

Got it working with the following method. There's probably a better way to do it but this is good enough for it's purpose.

Added IF statement for options

if($_POST['date'] === 'HIGH'){
    $order = 'meta_value_num';
    $sort = 'DESC';
}
elseif ($_POST['date'] === 'LOW'){
    $order = 'meta_value_num';
    $sort = 'ASC';
}
elseif ($_POST['date'] === 'ASC'){
    $order = 'date';
    $sort = 'ASC';
}
elseif ($_POST['date'] === 'DESC'){
    $order = 'date';
    $sort = 'DESC';
}

Then inside the $args

$args = array(
    'order' => $sort,
    'post_type' => 'product',
    'meta_key' => 'ek-product-price',
    'orderby' => $order,
)

Form

<select id="select1" type="text" name="date">
  <option value="ASC" type="hidden">ASC</option>
  <option value="DESC" type="hidden">DESC</option>
  <option value="HIGH" type="hidden">HIGH</option>
  <option value="LOW" type="hidden">LOW</option>
</select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.