WooCommerce后端按标题和SKU搜索

时间:2020-01-08 作者:Marco F

早上好,我正在尝试使用此功能扩展后端产品搜索,但没有成功。

This snippet works only in Title and i need to add also in Metakey SKU.

我已经尝试使用post\\u join和post\\u where进行扩展,如本例所示https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join但我不是问题专家。

请有人能帮我吗?提前谢谢。

function __search_by_title_only( $where, &$wp_query )
{
    global $wpdb,$typenow,$pagenow;

    if ( \'product\' === $typenow && isset( $_GET[\'s\'] ) && \'edit.php\' === $pagenow ) {
        $search_ids = array();
        $terms      = explode( \' \', $_GET[\'s\'] );

        foreach ( $terms as $term ) {
                if ( is_numeric( $term ) ) {
                    $search_ids[] = $term;
                }

                if ( $search_term = $_GET[\'s\'] ) {
                    $where .= \' AND \' . $wpdb->posts . \'.post_title LIKE \\\'%\' . esc_sql( like_escape( $term ) ) . \'%\\\'\';
                }

        }
        return $where;  
    }
}
add_filter(\'posts_search\', \'__search_by_title_only\', 500, 2);

1 个回复
SO网友:AHSAN KHAN

请尝试此代码

function search_by_sku( $search, &$query_vars ) {
        global $wpdb, $pagenow;
         if ( \'edit.php\' != $pagenow || ! is_search() || ! isset( $query_vars ->query_vars[\'s\'] ) || \'product\' != $query_vars ->query_vars[\'post_type\'] ) {
            return $search;
        }
        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 );