我需要允许用户能够通过一些自定义字段值对wp_query的结果进行排序。这些包括距离,日期和价格。距离和日期工作正常,但价格根本没有结果!
我认为我的问题是我排序的自定义字段是一个文本字段,我试图按数值排序。但是,如果我将字段设置为数字字段,我无法在数字中添加小数,是吗?
那么,当使用的自定义字段是文本字段时,是否有人知道通过数值获取wp_query的方法?
在这里,我的查询有助于:
$args = array(
// general
'post__in' => $postIDs,
'post_type' => 'event',
'posts_per_page' => 10,
'paged' => $paged,
'meta_key' => 'adult',
'orderby' => 'meta_value_num',
'order' => 'ASC',
// category filter
'tax_query' => $taxQuery,
// date filter
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'date_%_start-date',
'value' => $when,
'compare' => '>=',
'type' => 'NUMERIC'
),
array (
'key' => 'date_%_end-date',
'value' => $when2,
'compare' => '<=',
'type' => 'NUMERIC'
)
)
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query( $args );
修改
在以下答案之后,我可以编辑SQL查询以使用CAST
使元值成为整数。但是,我对语法不太确定,这就是我现在所想的,但它似乎不起作用:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID
FROM wp_posts
INNER JOIN wp_term_relationships
ON (wp_posts.ID = wp_term_relationships.object_id)
INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)
INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)
INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id)
WHERE 1=1
AND wp_posts.ID IN (66864,44870, ... more numbers ... ,66261,31361)
AND ( wp_term_relationships.term_taxonomy_id IN (2) )
AND wp_posts.post_type = 'event'
AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'private')
AND (CAST(wp_postmeta.meta_key = 'adult' AS UNSIGNED) // CAST attempt here...
AND (mt1.meta_key LIKE 'date_%_start-date' AND CAST(mt1.meta_value AS SIGNED) >= '20140619')
AND (mt2.meta_key LIKE 'date_%_end-date' AND CAST(mt2.meta_value AS SIGNED) <= '20140626') )
AND substr(wp_postmeta.meta_key, 1, 6) = substr(mt1.meta_key, 1, 6)
GROUP BY wp_posts.ID
ORDER BY wp_postmeta.meta_value+0 ASC
LIMIT 0, 10
修改
尝试使用float和ACF update_field将值更改为整数,但代码似乎没有出于某种原因做任何事情:
function update_adult_field( $value, $post_id, $field ) {
$value = (float) $value;
return $value;
}
add_filter('acf/update_value/name=adult', 'update_adult_field', 10, 3);
答案 0 :(得分:2)
如果我将字段设置为数字字段,则无法将小数添加到 号码,我可以吗?
我认为floatval()
在这里对你有用。它允许您获取字符串的浮点值。
$my_var = '1.3142';
$float_value_of_my_var = floatval( $my_var );
$float_value_of_my_var
将包含数值。
或者,您可以将变量转换为浮点数
(float) $my_var;