Adn*_*Ali 7 php wordpress search post woocommerce
我正在使用此代码从Wordpress/WooCommerce网站搜索产品.
我的要求是URL将像" http:// localhost/wp /?s = D34&post_type = product "同时s=D34是搜索字符串.
当用户搜索字符串时.将从所有默认字段+产品中搜索数据custom filed.下面的代码可以正常使用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' );
Run Code Online (Sandbox Code Playgroud)
这是为了防止不同的值
function cf_search_distinct( $where ) {
global $wpdb;
if ( is_search() ) {
return "DISTINCT"; //to prevent duplicates
}
return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );
Run Code Online (Sandbox Code Playgroud)
那么需要进行哪些修改?
URL http:// localhost/wp /?orderby = price&post_type =产品正常工作
尝试这个
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' );
Run Code Online (Sandbox Code Playgroud)
根据您更新的问题。
如果你曾经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')
Run Code Online (Sandbox Code Playgroud)
与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')
Run Code Online (Sandbox Code Playgroud)
记下wp1_posts.post_type并获得提示..对自己保持灵活性并尝试调试。以上是没有的结果$where .= " AND ($wpdb->posts.post_type = 'product') ";。
| 归档时间: |
|
| 查看次数: |
237 次 |
| 最近记录: |