Php Woocommerce-仅列出特定类别的商店页面产品
我只想在//商店页面上列出两个特定类别的产品。所有其余的将需要搜索或找到使用按钮,我已经在网站上 我尝试了一些不同的代码片段,但似乎什么都做不到我想要的 任何帮助都是徒劳的, 非常感谢Php Woocommerce-仅列出特定类别的商店页面产品,php,wordpress,woocommerce,categories,product,Php,Wordpress,Woocommerce,Categories,Product,我只想在//商店页面上列出两个特定类别的产品。所有其余的将需要搜索或找到使用按钮,我已经在网站上 我尝试了一些不同的代码片段,但似乎什么都做不到我想要的 任何帮助都是徒劳的, 非常感谢 Lewis我知道您只希望在/shop页面上显示特定的类别,对吗?因此,请使用下面的代码,将product_cat更改为您需要的样子 add_action('pre_get_posts','shop_filter_cat'); function shop_filter_cat($query) {
Lewis我知道您只希望在
/shop
页面上显示特定的类别,对吗?因此,请使用下面的代码,将product_cat更改为您需要的样子
add_action('pre_get_posts','shop_filter_cat');
function shop_filter_cat($query) {
if (!is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query()) {
$query->set('tax_query', array(
array ('taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'type-1'
)
)
);
}
}
WooCommerce页面对此进行了解释,您只需根据自己的需要进行更改 在您的情况下,将运算符更改为“In”,然后 terms=>数组('刀') 到 terms=>array('your-cat-slug-1'、'your-cat-slug-2')
将此代码放在Child-themes-functions.php文件中。代码在哪里。显示您的代码。回复有点晚抱歉,但我已经测试了这个代码段,我认为它正在做我需要的一切,然后意识到它不仅允许在/shop页面中侦听某些产品类别,而且还允许在搜索中显示这些类别。有没有办法只允许在/商店页面上显示某些类别,但搜索仍将搜索所有产品。我不确定,现在无法测试。但是如果(!is_admin()&&!is_search()&&is_shop())可能会起作用。
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
function custom_pre_get_posts_query( $q ) {
if ( ! $q->is_main_query() ) return;
if ( ! $q->is_post_type_archive() ) return;
if ( ! is_admin() && is_shop() ) {
$q->set( 'tax_query', array(array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'your-cat-slug-1' , 'your-cat-slug-2' ), // Display products in the your-cat-slug-1/your-cat-slug-2 category on the shop page
'operator' => 'IN'
)));
}
remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
}