0

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");
Astron
  • 1,211
  • 5
  • 20
  • 42
  • Have you considered just using `WHERE OR ...`? – fubar Mar 16 '18 at 02:36
  • This will help you: https://stackoverflow.com/questions/907806/passing-an-array-to-a-query-using-a-where-clause – jose_bacoy Mar 16 '18 at 03:05
  • @fubar, yes, please see the linked question. In my case, I do not know how many conditions there will be. @anonyXmous isn't what you referenced similar do what I am already doing? Issue is I need to support `LIKE` matches for each `IN` match. – Astron Mar 16 '18 at 03:17
  • That shouldn't be an issue. Will your conditions be in an array or something? – fubar Mar 16 '18 at 03:19

1 Answers1

0

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}" ));
Astron
  • 1,211
  • 5
  • 20
  • 42