MySQL LIKE语句支持多个查询

时间:2018-03-16 02:32:24

标签: mysql wordpress

想要使用部分匹配找到产品名称,例如product_name cat-in-the-hat name cat ,然后将返回ID。目前,需要精确匹配,即不可能进行部分匹配。

LIKE语句通常会起作用,但我们使用IN语句来支持不同数量的输入。每MySQL LIKE IN()?REGEXP也应该有效,但如上所述,输入数量各不相同。为每个name实例执行匹配的理想方法是什么?

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");

1 个答案:

答案 0 :(得分:0)

我无法得到你的工作答案。以下是我能够根据Array in Mysql WHERE LIKE?

检索所需功能的方法
$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}" ));