我想使用自定义的帖子类型元框查询名字和姓氏
我正在使用的代码:
$name = \'John Doe\';
$args = array(
\'post_type\' => \'customers\',
\'post_status\' => array( \'publish\', \'pending\', \'draft\' ),
\'numberposts\' => -1,
\'order\' => \'ASC\',
\'orderby\' => \'meta_value\',
\'meta_key\' => \'customer_first_name\'
\'meta_query\' => array(
\'relation\' => \'OR\',
array(
\'key\' => \'customer_first_name\',
\'value\' => $name,
\'compare\' => \'LIKE\',
),
array(
\'key\' => \'customer_last_name\',
\'value\' => $name,
\'compare\' => \'LIKE\',
),
),
);
$customers = get_posts($args);
$num = count( $customers );
如果我只搜索“John”,就会显示结果。如果我搜索全名“JohnDoe”,则没有结果。为什么会这样?
最合适的回答,由SO网友:Eduardo Escobar 整理而成
$name = \'John Doe\';
// Split $name
$name = preg_split( \'/\\s+/\', trim( $name ) );
// Set first name
$first_name = $name[0];
// Last name was provided?
$last_name = isset( $name[1] ) ? $name[1] : null;
// Define meta query args array
$meta_query_args = array();
// Set "first name" meta query or "first name" + "last name" if both exist
if ( is_null( $last_name ) ) {
$meta_query_args[] = array(
\'key\' => \'customer_first_name\',
\'value\' => $first_name,
\'compare\' => \'LIKE\',
);
} else {
$meta_query_args[] = array(
\'relation\' => \'AND\', // This is default, just trying to be descriptive
array(
\'key\' => \'customer_first_name\',
\'value\' => $first_name,
\'compare\' => \'LIKE\'
),
array(
\'key\' => \'customer_last_name\',
\'value\' => $last_name,
\'compare\' => \'LIKE\'
)
);
}
// Set \'meta_query\' in your $args variable
$args[\'meta_query\'] = $meta_query_args;
注意,除了“first name”+“last name”(顺序问题)之外,还必须添加额外的代码来支持“last name”+“first name”(姓氏)。