我正在使用 this code从 Wordpress 搜索产品/WooCommerce网站。
我的要求是 URL 类似于“http://localhost/wp/?s=D34&post_type=product”
s=D34
是搜索字符串。
用户何时搜索字符串。将从所有默认字段+产品的自定义字段
中搜索数据。以下代码适用于 http://localhost/wp/?s=D34但是当 &post_type=product
与 url 连接时,它会显示
代码如下
function cf_search_where( $where ) {
global $pagenow, $wpdb;
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND ($wpdb->posts.post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
这是为了防止不同的值
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT"; //to prevent duplicates
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
那么需要做什么修改呢?
URL
http://localhost/wp/?orderby=price&post_type=product工作正常
最佳答案
试试这个
function cf_search_where( $where ) {
global $pagenow, $wpdb;
// a little debugging will help you..
//print_r ($where);
//die();
if ( is_search() ) {
$where = preg_replace("/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
$where .= " AND ($wpdb->posts.post_type = 'product') ";
}
return $where;
}
add_filter( 'posts_where', 'cf_search_where' );
基于您更新的问题。
如果您使用 print_r ($where);
来检查 $where
包含什么值,您将看到类似这些的内容...
AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%')))
AND (wp1_posts.post_password = '')
AND wp1_posts.post_type IN ('post', 'page', 'attachment', 'product')
AND (wp1_posts.post_status = 'publish')
与http://localhost/wp/?s=D34&post_type=product
AND (((wp1_posts.post_title LIKE '%D34%') OR (wp1_postmeta.meta_value LIKE '%D34%') OR (wp1_posts.post_content LIKE '%D34%')))
AND (wp1_posts.post_password = '')
AND ( ( wp1_postmeta.meta_key = '_visibility' AND CAST(wp1_postmeta.meta_value AS CHAR) IN ('visible','search') ) )
AND wp1_posts.post_type = 'product'
AND (wp1_posts.post_status = 'publish')
记下 wp1_posts.post_type
并获得提示.. 灵活对待自己并尝试调试。以上是没有 $where .= "AND ($wpdb->posts.post_type = 'product') ";
的结果。
关于php - 使用 WooCommerce 产品搜索搜索特定 post_type 表单 post_type 列时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349462/