有没有办法可以用woocommerce产品搜索覆盖主题的搜索查询。我想要在页面和帖子中搜索内容,而不是搜索产品。
我搜索并发现了这个:
function custom_search_query($where, &$wp_query)
{
global $wpdb;
if ( empty( $where ))
return $where;
// get search expression
$terms = $wp_query->query_vars[ 's' ];
$where = 'wp_posts.post_type = "product"';
// get searcheable_acf, a list of advanced custom fields you want to search content in
$list_searcheable_acf = list_searcheable_acf();
foreach( $exploded as $tag ) :
$where .= "
AND (
(wp_posts.post_type LIKE '%$tag%')
OR (wp_posts.post_content LIKE '%$tag%')
OR EXISTS (
SELECT * FROM wp_postmeta
WHERE post_id = wp_posts.ID
AND (";
foreach ($list_searcheable_acf as $searcheable_acf) :
if ($searcheable_acf == $list_searcheable_acf[0]):
$where .= " (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') ";
else :
$where .= " OR (meta_key LIKE '%" . $searcheable_acf . "%' AND meta_value LIKE '%$tag%') ";
endif;
endforeach;
$where .= ")
)
OR EXISTS (
SELECT * FROM wp_comments
WHERE comment_post_ID = wp_posts.ID
AND comment_content LIKE '%$tag%'
)
OR EXISTS (
SELECT * FROM wp_terms
INNER JOIN wp_term_taxonomy
ON wp_term_taxonomy.term_id = wp_terms.term_id
INNER JOIN wp_term_relationships
ON wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id
WHERE (
taxonomy = 'post_tag'
OR taxonomy = 'category'
OR taxonomy = 'myCustomTax'
)
AND object_id = wp_posts.ID
AND wp_terms.name LIKE '%$tag%'
)
)";
endforeach;
return $where;
}
add_filter( 'posts_search', 'custom_search_query', 500, 2 );
但是这会在搜索中添加高级自定义字段。我想只搜索产品。
这可能吗?
提前致谢。
答案 0 :(得分:0)
您应该使用pre_get_posts过滤器来过滤搜索结果页中的帖子类型。例如:
add_filter( 'pre_get_posts', 'custom_pre_get_posts' );
function custom_pre_get_posts( $query ) {
if ( is_search() ) {
$query->set('post_type', 'product');
}
return $query;
}
这里唯一的问题是,如果您的产品具有自定义字段或属性,它们将不会包含在结果中,因为默认的WordPress搜索仅在标题和内容中查找。 您提供的示例具有更复杂的搜索,它也可以在自定义字段中查找。但如果主要目标是删除除产品之外的所有内容,我的代码就可以解决问题。
答案 1 :(得分:0)
以下代码应仅搜索“产品”帖子类型,并显示在您的普通搜索档案中。通过在name属性中使用'post_type',您可以声明要搜索的帖子类型。
<form action="<?php bloginfo('siteurl'); ?>" method="get" class="form-inline searchform">
<input type="text" name="s" value="" placeholder="Search for Products..." class="s" />
<input type="hidden" name="post_type[]" value="product" />
<button type="submit" class="searchsubmit">Search</button>
</form>