0

Good morning, i'm trying to extend backend product search by using this function without success.

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

I have tried extend by using post_join and post_where as in this example https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join but i'm not expert on queries.

Please anyone can help me ? Thanks in advance.

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);
0

Please try this code

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.