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");
4
  • Have you considered just using WHERE <condition> OR <condition> ...? Commented Mar 16, 2018 at 2:36
  • This will help you: stackoverflow.com/questions/907806/… Commented Mar 16, 2018 at 3: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. Commented Mar 16, 2018 at 3:17
  • That shouldn't be an issue. Will your conditions be in an array or something? Commented Mar 16, 2018 at 3:19

1 Answer 1

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}" ));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.