skip to Main Content

I have those products:

Name1 SECONDNAME 1 
Name1 SECONDNAME 2
Name1 SECONDNAME something
Name1 SECONDNAME something 5
Name2 SECONDNAME 1
Name2 SECONDNAME 2
Name2 SECONDNAME something
Name2 SECONDNAME something 5

I want to list them like this:

    $query = new WC_Product_Query( array(
        'title' => 'Name1 SECONDNAME *'
    ) );
    $products = $query->get_products();

2

Answers


  1. Rather than WC_Product_Query, you could use WP_Query and the sentence parameter (tested):

    $query = new WP_Query( array(
        'post_type'      => 'product',
        's'              => 'Name1 SECONDNAME ',
        'sentence'       => true,
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'no_found_rows'  => true,
    ) );
    
    if ( $query->have_posts() ) {
        $products = array_map( 'get_product', $query->posts );
    }
    
    Login or Signup to reply.
  2. Here is a function that you can call where you need it. Add it in your functions.php file

    function get_product_ids_by_title($search_string) {
        global $wpdb;
    
        $table_name = $wpdb->prefix . 'posts';
        $post_type = 'product';
    
        $query = $wpdb->prepare(
            "SELECT ID
            FROM $table_name
            WHERE post_type = %s
            AND post_title LIKE %s",
            $post_type,
            $wpdb->esc_like($search_string) . '%'
        );
    
        $product_ids = $wpdb->get_col($query);
    
        return $product_ids;
    }
    

    Usage:

    $search_string = 'your_search_string';
    $product_ids = get_product_ids_by_title($search_string);
    
    // Output the retrieved product IDs
    foreach ($product_ids as $product_id) {
        echo $product_id . '<br>';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search