php - 使用 WooCommerce 产品搜索搜索特定 post_type 表单 post_type 列时出错

标签 php wordpress search post woocommerce

我正在使用 this codeWordpress 搜索产品/WooCommerce网站。
我的要求是 URL 类似于“http://localhost/wp/?s=D34&post_type=products=D34 是搜索字符串。

用户何时搜索字符串。将从所有默认字段+产品的自定义字段中搜索数据。以下代码适用于 http://localhost/wp/?s=D34但是当 &post_type=product 与 url 连接时,它会显示 enter image description here

代码如下

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工作正常

但是http://localhost/wp/?s=D34&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 包含什么值,您将看到类似这些的内容...

http://localhost/wp/?s=D34

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/

相关文章:

php - 使用带套接字对的 zlib 过滤器

javascript - 如果 $thisPage 等于特定页面则结束函数

javascript - WordPress 插件未加载 Javascript 文件

php - 将产品自定义字段添加到 WooCommerce 中的管理产品批量编辑表单

java - 是否有纯 Java NSSearchField 替代品?

php - 从 MP3 PHP 获取专辑封面

php - 选择不同的月份和年份,然后分割值

javascript - 页面打开时菜单打开(下拉)

Ruby 字谜求解器

java - 不区分大小写的搜索和替换