我尝试将其包含在默认搜索自定义字段中。我在这里点击了链接
http://jamescollings.co.uk/blog/extending-woocommerce-search-query-include-custom-fields/
我从中创建了一个小插件,该插件可以获取我的自定义选择字段和自定义文本,并且具有以下内容
<?php
/**
* Add sku, author, publisher and format to product search
*/
// hook into wp pre_get_posts
add_action('pre_get_posts', 'jc_woo_search_pre_get_posts');
/**
* Add custom join and where statements to product search query
* @param mixed $q query object
* @return void
*/
function jc_woo_search_pre_get_posts($q){
if ( is_search() ) {
add_filter( 'posts_join', 'jc_search_post_join' );
add_filter( 'posts_where', 'jc_search_post_excerpt' );
}
}
/**
* Add Custom Join Code for wp_mostmeta table
* @param string $join
* @return string
*/
function jc_search_post_join($join = ''){
global $wp_the_query;
// escape if not woocommerce searcg query
if ( empty( $wp_the_query->query_vars['wc_query'] ) || empty( $wp_the_query->query_vars['s'] ) )
return $join;
$join .= "INNER JOIN wp_postmeta AS jcmt1 ON (wp_posts.ID = jcmt1.post_id)";
return $join;
}
/**
* Add custom where statement to product search query
* @param string $where
* @return string
*/
function jc_search_post_excerpt($where = ''){
global $wp_the_query;
// escape if not woocommerce search query
if ( empty( $wp_the_query->query_vars['wc_query'] ) || empty( $wp_the_query->query_vars['s'] ) )
return $where;
$where = preg_replace("/post_title LIKE ('%[^%]+%')/", "post_title LIKE $1)
OR (jcmt1.meta_key = '_sku' AND CAST(jcmt1.meta_value AS CHAR) LIKE $1)
OR (jcmt1.meta_key = '_text_field' AND CAST(jcmt1.meta_value AS CHAR) LIKE $1)
OR (jcmt1.meta_key = '_select' AND CAST(jcmt1.meta_value AS CHAR) LIKE $1 ", $where);
return $where;
}
?>
但是什么也没发生,我该如何解决 谢谢
答案 0 :(得分:0)
这是非常简单的代码,只需将其粘贴到您的functions.php文件中即可。
function woo_custom_search( $query ) {
if( ! is_admin() && $query->is_main_query() ) {
if ( $query->is_search() ) {
$meta_query = $query->get( 'meta_query' );
$meta_query[] = array(
'key' => 'custom_field_name',
'value' => $query->query['s'],
'compare' => 'LIKE'
);
$query->set( 'meta_query', $meta_query );
}
}
}
add_action( 'woocommerce_product_query' , 'woo_custom_search' );
参考: