我有一个正在工作的查询,它调用我的所有帖子,这些帖子对于两个元键中的一个具有特定的元值:
$term = filter_var( $_GET[\'term\'] );
$query = get_posts( [
\'post_type\' => \'some_cpt_name\',
\'meta_query\' => [
\'relation\' => \'OR\',
[
\'key\' => \'foo\',
\'value\' => $term,
\'compare\' => \'LIKE\',
],
[
\'key\' => \'bar\',
\'value\' => $term,
\'compare\' => \'LIKE\',
],
]
] );
我需要查询所有具有
$term
作为元键“foo”或“bar”或作为帖子标题。问题是,如何将帖子标题添加为其他可能的关键字?
Q: 如何检查$term
也许是在post_title
?
SO网友:kaiser
好的,下面是使用posts_clauses
根据@scribu的建议进行筛选(和编辑):
function alter_posts_where_clause( $where )
{
global $wpdb;
$term = filter_var( trim( $_GET[\'term\'] ), FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE );
if ( is_null( $term ) )
return $where;
$term = $wpdb->esc_like( $term );
// Append to the WHERE clause:
$where .= $wpdb->prepare( " OR {$wpdb->posts}.post_title LIKE \'%s\'", "%{$term}%" );
return $where;
}
add_filter( \'posts_where\', \'alter_posts_where_clause\' );