WP_QUERY按Meta_Value_Num或日期排序

时间:2017-09-25 作者:scopeak

我正在使用meta_value_num 按价格对帖子进行排序,并允许用户使用下拉列表在最大值和最小值之间进行更改。我现在需要的是能够从Min PriceMax PriceNewest PostedOldest Posted 是否可以按多个值排序?

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>

1 个回复
最合适的回答,由SO网友:scopeak 整理而成

使用以下方法进行操作。也许有更好的方法可以做到这一点,但这就足够了。

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>

结束