想要使用部分匹配找到产品名称,例如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");
答案 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}" ));