简体   繁体   English

按数字自定义字段对WordPress帖子进行排序

[英]Sort WordPress posts by numerical custom fields

I added a code that allows me to sort WordPress posts by custom fields. 我添加了一个代码,允许我按自定义字段对WordPress帖子进行排序。 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 这是代码: 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 http://wordpress.org/support/topic/sort-posts-by-custom-field-in-backend

If you would like to do it manually (though the answers referencing WP_Query are better options), a reasonably nice treatment might use array_multisort : 如果你想手动完成(尽管引用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);

Use the WP_Query class and the orderby=meta_value_num parameter to sort numerically. 使用WP_Query类和orderby = meta_value_num参数进行数字排序。 Also, make sure you store the price in the custom field as a number without the "$" prepended. 此外,请确保将自定义字段中的价格存储为不带“$”前缀的数字。

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

$query then contains rows of posts sorted numerically by price. $query然后包含按价格按数字排序的帖子行。

I haven't had a look at your code but you this has to do with the numbers being strings in your case. 我没看过你的代码,但是这与你的情况下的字符串数字有关。 If you sort a string it is sorted like you describe. 如果对字符串进行排序,则会按照您的描述进行排序。 In order to sort it by it's value you need to remove the $ sign and cast it to a number. 为了按它的值进行排序,您需要删除$符号并将其转换为数字。

Did you see this technique? 你看到这种技术吗? - adding zero to the meta value of the to force it to be treated as an integer. - 将0添加到元的值以强制将其视为整数。 The post has been updated various times over the years too so it might help you; 多年来,该帖子已经多次更新,因此它可能对您有所帮助;

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

function order($a, $b) {return intval($b) - intval($a);}
uasort($array, 'order');

I wonder that can help you ;) 我想知道可以帮到你;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM