MySQL LIKE 语句支持多个查询

标签 mysql wordpress

想要使用部分匹配来查找产品名称,例如,如果product_namecat-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");

最佳答案

我无法根据 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}" ));

关于MySQL LIKE 语句支持多个查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312303/

相关文章:

php - 从 mysql php jquery ajax 读取数据

html - 调整页面大小时添加空格 -css

php - 在 Woocommerce 中以编程方式应用优惠券

php - 提交表单后出现错误时间 Php Mysql Strtotime

php - (Laravel) 无法将 group by 与 order by 一起使用

django - WordPress 漂亮的永久链接故障转移 SSL - 404 文件不存在

php - 仅将列添加到 WordPress 管理员的帖子,而不是自定义帖子类型

javascript - WordPress 中未检查的runtime.lastError : The message port closed before a response was received.

php - PHP MySQL中日期和时间的计算和echo

php - 查询返回冗余结果之间的MySQL