我正在尝试扩展ADMIN WooCommerce产品搜索以包含自定义字段(例如我通过函数添加的_sku_2)
使用this as a guide,我尝试将此代码添加到我的函数中,但没有运气:
// EXTEND ADMIN PRODUCT SEARCH
add_action( 'pre_get_posts', 'extend_admin_search' );
function extend_admin_search( $query ) {
// Extend search for document post type
$post_type = 'product';
// Custom fields to search for
$custom_fields = array(
"_supplier_sku",
"_sku_2"
);
if( ! is_admin() )
return;
if ( $query->query['post_type'] != $post_type )
return;
$search_term = $query->query_vars['s'];
// Set to empty, otherwise it won't find anything
//$query->query_vars['s'] = '';
if ( $search_term != '' ) {
$meta_query = array( 'relation' => 'OR' );
foreach( $custom_fields as $custom_field ) {
array_push( $meta_query, array(
'key' => $custom_field,
'value' => $search_term,
'compare' => 'LIKE'
));
}
$query->set( 'meta_query', $meta_query );
};
}
似乎根本没有编辑查询结果。甚至使用默认查询进行产品搜索?
答案 0 :(得分:1)
另一种方法是扩展管理产品搜索自定义帖子元键值:
add_filter( 'posts_search', 'extend_product_search', 20, 2 );
function extend_product_search( $where, $query ) {
global $pagenow, $wpdb;
if ( 'edit.php' != $pagenow || ! is_search() || ! isset( $query->query_vars['s'] ) || 'product' != $query->query_vars['post_type'] ) {
return $where;
}
// Here your post meta keys
$meta_keys = array('_supplier_sku', '_sku_2');
$meta_keys = implode("','", $meta_keys);
// get the search value
$term = sanitize_text_field( $query->query_vars['s'] );
// Light SQL Query to get the corresponding product IDs
$search_ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts as p
LEFT JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE pm.meta_key IN ('$meta_keys') AND pm.meta_value LIKE '%$term%'" );
// Cleaning
$search_ids = array_filter( array_unique( array_map( 'absint', $search_ids ) ) );
// Alter the WHERE clause in the WP_Query search
if ( count( $search_ids ) > 0 ) {
$where = str_replace( 'AND (((', "AND ( ({$wpdb->posts}.ID IN (" . implode( ',', $search_ids ) . ")) OR ((", $where );
}
return $where;
}
代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。