WooCommerce search products by tag or description Query Posts

I want to write the custom query to search product by its description. By default the WooCommerce search doesn’t include the searching by description. I am using the query_posts function to get products. Here is my code:

$args = array(
    's'                   => $search_keyword,
    'post_type'           => 'product',
    'post_status'         => 'publish',
    'ignore_sticky_posts' => 1,
    'meta_query'          => array(
       array(
        'key'     => '_visibility',
        'value'   => array( 'search', 'visible' ),
        'compare' => 'IN'
        )
      )
   );
$products = get_posts( $args );

Related posts

Leave a Reply

1 comment

  1. If you are wanting to search the product description, you are going to have to search the post_content. I don’t think you’ll be able to do that using get_posts() or WP_Query(). The only way to do that is to write a custom SQL query.

    For your example, you’d need something like the following:

    function enhanced_product_search( $keyword ) {
        global $wpdb;
    
        // Manually build SQL query and get results (this query will return only IDs)
        $search_results = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT posts.ID 
                FROM ssod_posts AS posts
                    LEFT JOIN ssod_postmeta AS meta ON meta.post_id = posts.ID
                WHERE posts.post_type = 'product'
                    AND posts.post_status = 'publish'
                    AND meta.meta_key = '_visibility'
                    AND meta.meta_value IN ('search', 'visible')
                    AND ( posts.post_title LIKE '%{$keyword}%' OR posts.post_content LIKE '%{$keyword}%' );"
            ),
            'ARRAY_N'
        );
    
        $products = [];
    
        // Loop over search results to get products from their IDs
        foreach ( $search_results as $result ) {
            $products[] = wc_get_product( $result[0] );
        }
    
        return $products;
    }