如果你在WP_QUERY中传递这些args时看到下面的代码,那么它将生成一个查询,它会将%包裹在测试中 像这样的东西
" AND CAST(wp_postmeta.meta_value AS CHAR) LIKE '%test%') ) "
有没有可能我想在'test'字符串的开头只有%?
$args = array(
'post_type' => 'job_listing',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'geo_address',
'value' => 'test',
'compare' => 'LIKE'
)
)
);
答案 0 :(得分:0)
你不能这样做,因为wp_query
自动添加%..%。但是,您可以使用自定义查询执行此操作,例如;
global $wpdb;
$specific_posts = $wpdb->get_results("SELECT * FROM `wp_posts` WHERE
post_type='job_listing' AND post_status ='publish' AND ID
IN(
SELECT post_id FROM `wp_postmeta` WHERE meta_key='geo_address'
AND meta_value LIKE '%test'
) ORDER BY post_date DESC");
修改:如果您不想使用自定义查询执行此操作,则需要使用wp之类的posts_where操作;
add_filter( 'posts_where', 'custom_posts_where', 10, 2 );
function custom_posts_where( $where, &$wp_query )
{
global $wpdb;
if ( $custom_post_meta_value = $wp_query->get( 'custom_value' ) ) {
$where .= ' AND ' . $wpdb->postmeta . '.meta_key = "geo_address" AND ' . $wpdb->postmeta . '.meta_value LIKE \'' . esc_sql( like_escape( $custom_post_meta_value ) ) . '\'';
}
return $where;
}
在您的查询中,使用如下所示;
$args = array(
'post_type' => 'job_listing',
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'meta_query' => array(
array(
'key' => 'geo_address',
'custom_value' => '%test',
'compare' => 'LIKE'
)
)
);
答案 1 :(得分:0)
这是另一个解决方案,我想我会尝试两个
function filter_meta_query( $pieces ) {
if ( !empty( $pieces['where'] ) ) {
$pieces['where'] = preg_replace( '/(.*?)LIKE \'\%(.*?)\%\'/', "\$1LIKE '\$2%'", $pieces['where'] );
}
return $pieces;
}
add_filter( 'get_meta_sql', 'filter_meta_query' );
$args = array(
'meta_query' => array(
array(
'key' => 'any_key',
'compare' => 'LIKE',
'value' => '%test'
)
)
);
// the query
$query = new WP_Query( $args );
// remove it after the query.
remove_filter( 'get_meta_sql', 'filter_meta_query' );
答案 2 :(得分:0)
似乎这篇文章解决了使用REGEX而不是LIKE的问题: https://wordpress.stackexchange.com/questions/159426/meta-query-with-string-starting-like-pattern