我正在使用Divi WP主题,我的标题中包含以下代码:
<form role="search" method="get" class="et-search-form" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<?php
printf( '<input type="search" class="et-search-field" placeholder="%1$s" value="%2$s" name="s" title="%3$s" />',
esc_attr__( 'Search …', 'Divi' ),
get_search_query(),
esc_attr__( 'Search for:', 'Divi' )
);
?>
</form>
我需要在搜索结果以及页面和帖子中显示WooCoomerce产品。
我尝试添加:
<input type="hidden" value="product" name="post_type" id="post_type" />
但是这样做现在只显示WooCommerce产品,不再显示页面/帖子。
由于
答案 0 :(得分:2)
您需要使用pre_get_posts
过滤器
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array('post', 'product'));
$meta_query = array(
'relation' => 'AND',
array(
'key' => '_visibility',
'value' => 'visible',
'compare' => 'IN'
),
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '='
)
);
$query->set('meta_query', $meta_query);
}
}
}
add_action('pre_get_posts','search_filter');
在子主题的functions.php中添加此内容,当然您可以在定义post_type
(页面,优惠券)的数组中删除或添加任何帖子类型。
为确保只检索可用的产品,我们需要根据Woocommerce自定义字段设置一个特殊的meta_query
。
希望它的帮助!