phpmysqlwordpress

MySQL LIKE statement supporting multiple queries


Would like to find product names using partial matches, e.g if product_name is cat-in-the-hat and name is cat, then the ID will be returned. Currently, an exact match is required, i.e. a partial match is not possible.

A LIKE statement would typically work but we are using an IN statement in order to support a varying number of inputs. Per MySQL LIKE IN()? a REGEXP should also work but as mentioned the number of inputs vary. What would be the ideal way to perform matches for each name instance?

function woo_products_by_name_shortcode( $atts, $content = null ) {

    // Get attribuets
    extract(shortcode_atts(array(
        'name' => ''
    ), $atts));

    if( empty($name) ) return;

    // Format product slugs string
    $name = str_replace(",", "','", $name);

    global $wpdb;
    // Get the corresponding products ids for each name
    $ids = $wpdb->get_col( "SELECT ID FROM {$wpdb->prefix}posts
        WHERE post_type = 'product' AND post_name IN('$name')" );

    ob_start();

    // Define Query Arguments
    $loop = new  WP_Query( array(
        'post_type'      => 'product',
        'posts_per_page' => -1,
        'post__in'       => $ids
    ));

    // Get products number
    $product_count = $loop->post_count;

    echo '<pre>'; print_r($loop->posts); echo '</pre>';

    return ob_get_clean();
}
add_shortcode("woo_products_by_name", "woo_products_by_name_shortcode");

Solution

  • I was unable to solve based on Array in Mysql WHERE LIKE?. Below is how I was able to make it work:

    $array_name = explode(",", $atts['name']);
    
    global $wpdb;
    // Get the corresponding products ids for each name
    $query_parts = array();
    foreach ($array_name as $val) {
        $query_parts[] = "'%%".$val."%%'";
    }
    
    $string = implode(' OR post_name LIKE ', $query_parts);
    $ids = $wpdb->get_col($wpdb->prepare( "SELECT ID FROM {$wpdb->prefix}posts
        WHERE post_type = 'product' AND post_name LIKE {$string}" ));