1

I added a code that allows me to sort WordPress posts by custom fields. I'm trying to sort the posts by prices, but it's sorting by the first number and not the value:

$116.99
$12.95
$149.00
$15.99

Instead of:

$12.95
$15.99
$116.99
$149.00

How can I get it to sort properly?

Here's the code: http://pastebin.com/Pe5yfvrE

I took it from this discussion, but it was left unresolved there..

http://wordpress.org/support/topic/sort-posts-by-custom-field-in-backend

4

5 回答 5

3

如果您想手动进行(尽管引用的答案WP_Query是更好的选择),一个相当不错的处理可能会使用array_multisort

$arr = array(
  '$116.99',
  '$12.95',
  '$149.00',
  '$15.99'
);

$keys = array();

foreach ($arr as $value) {
    $keys[] = floatval(substr($value, 1));
}

array_multisort($keys, SORT_ASC, $arr);
于 2012-07-09T21:28:17.727 回答
1

使用WP_Query 类和 orderby=meta_value_num 参数进行数字排序。此外,请确保您将价格作为数字存储在自定义字段中,并且不带“$”。

$query = new WP_Query( array ( 'orderby' => 'meta_value_num', 'meta_key' => 'price' ) );

$query然后包含按价格数字排序的帖子行。

于 2012-07-09T21:24:03.910 回答
0

我没有看过你的代码,但你这与你的情况下的数字是字符串有关。如果你对一个字符串进行排序,它会像你描述的那样排序。为了按它的值对其进行排序,您需要删除该$符号并将其转换为一个数字。

于 2012-07-09T21:22:27.477 回答
0

你见过这种技术吗?- 将零添加到 的元值以强制将其视为整数。多年来,该帖子也已多次更新,因此可能会对您有所帮助;

http://wordpress.org/support/topic/order-by-meta_key-where-meta_value-is-number?replies=11

于 2012-07-09T21:24:28.943 回答
0
function order($a, $b) {return intval($b) - intval($a);}
uasort($array, 'order');

我想知道这可以帮助你;)

于 2012-07-09T21:33:07.447 回答