想要使用部分匹配来查找产品名称,例如,如果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");
最佳答案
我无法根据 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/