我在添加meta_value
在WooCommerce SKU的搜索查询中。默认情况下,按SKU搜索仅对管理员有效。
我想进行前端搜索,接受搜索中的SKU。
注意:SKU不在产品标题中。因此,我需要创建一个自定义查询。
function SearchFilter($query) {
if ($query->is_search) {
$meta_query_args = array(
\'relation\' => \'OR\',
array(
\'key\' => \'_sku\',
\'value\' => $query->query_vars[\'s\'],
\'compare\' => \'=\',
)
);
$query->set(\'post_type\', array(\'post\',\'page\', \'product\'));
$query->set(\'post_status\', array(\'publish\'));
$query->set(\'meta_query\', $meta_query_args);
}
return $query;
}
add_filter(\'pre_get_posts\',\'SearchFilter\');
The problem : 当我放置此代码并打印当前SQL请求时,它会给我类似的结果。
SELECT SQL_CALC_FOUND_ROWS bhd_posts.ID FROM bhd_posts INNER JOIN bhd_postmeta ON ( bhd_posts.ID = bhd_postmeta.post_id ) WHERE 1=1 AND (((bhd_posts.post_title LIKE \'%96242-20VH%\') OR (bhd_posts.post_excerpt LIKE \'%96242-20VH%\') OR (bhd_posts.post_content LIKE \'%96242-20VH%\'))) AND (bhd_posts.post_password = \'\') AND (
( bhd_postmeta.meta_key = \'_sku\' AND bhd_postmeta.meta_value = \'96242-20VH\' )
) AND bhd_posts.post_type IN (\'post\', \'page\', \'product\') AND ((bhd_posts.post_status = \'publish\')) GROUP BY bhd_posts.ID ORDER BY bhd_posts.post_title LIKE \'%96242-20VH%\' DESC, bhd_posts.post_date DESC LIMIT 0, 10
正如您所看到的,它试图获取;经典部分“;在表格中
x_posts
对于
post_title
或
post_excerpt
或
post_content
AND 它必须有一个
meta_value
我的SKU。
如上所述,我的产品标题中没有sku。
Goal : 必须在标题、摘录、内容或meta\\u值中搜索,或使用meta\\u值进行独家搜索。
SO网友:AHSAN KHAN
如果您使用的是wordpress搜索,则可以添加此代码以使其正常工作
function search_by_sku( $search, &$query_vars ) {
global $wpdb;
if(isset($query_vars->query[\'s\']) && !empty($query_vars->query[\'s\'])){
$args = array(
\'posts_per_page\' => -1,
\'post_type\' => \'product\',
\'meta_query\' => array(
array(
\'key\' => \'_sku\',
\'value\' => $query_vars->query[\'s\'],
\'compare\' => \'LIKE\'
)
)
);
$posts = get_posts($args);
if(empty($posts)) return $search;
$get_post_ids = array();
foreach($posts as $post){
$get_post_ids[] = $post->ID;
}
if(sizeof( $get_post_ids ) > 0 ) {
$search = str_replace( \'AND (((\', "AND ((({$wpdb->posts}.ID IN (" . implode( \',\', $get_post_ids ) . ")) OR (", $search);
}
}
return $search;
}
add_filter( \'posts_search\', \'search_by_sku\', 999, 2 );