扩展管理产品搜索WooCommerce中的自定义元字段



我正在尝试将管理员woocommerce产品搜索扩展到包括自定义字段(例如,我通过函数添加的_sku_2(

管理员产品搜索

以此为指导,我尝试将此代码添加到我的功能中,但没有运气:

// 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 );
     };
}

似乎根本没有编辑查询结果。产品搜索是否使用默认查询?

这种另一种方法可以扩展管理产品搜索以自定义邮政密钥值:

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文件中。测试和工作。

最新更新