Mr.*_* Jo 5 php wordpress product metadata woocommerce
I need to filter the WooCommerce shop page and only want to display products which expects a custom product meta data. This is what I've found in the archive-product.php:
/**
* Hook: woocommerce_before_shop_loop.
*
* @hooked wc_print_notices - 10
* @hooked woocommerce_result_count - 20
* @hooked woocommerce_catalog_ordering - 30
*/
do_action( 'woocommerce_before_shop_loop' );
woocommerce_product_loop_start();
if ( wc_get_loop_prop( 'total' ) ) {
while ( have_posts() ) {
the_post();
/**
* Hook: woocommerce_shop_loop.
*
* @hooked WC_Structured_Data::generate_product_data() - 10
*/
do_action( 'woocommerce_shop_loop' );
wc_get_template_part( 'content', 'product' );
}
}
woocommerce_product_loop_end();
Run Code Online (Sandbox Code Playgroud)
So how can I pass filter values in this part to only show the products with meta key X and value Y?
Update
I've tried it the way Loic said but when I check more then one meta value it's causing problems and I can't see any products:
add_filter( 'woocommerce_product_query_meta_query', 'show_only_products_with_specific_metakey', 10, 2 );
function show_only_products_with_specific_metakey( $meta_query, $query ) {
// Only on shop pages
if( ! is_shop() ) return $meta_query;
$meta_query[] = array(
'key' => '_the_meta_key',
'value' => 'the_value',
'compare' => 'EXIST'
);
//Don't works when adding the second one
$meta_query[] = array(
'key' => '_the_meta_key',
'value' => 'the_value_2',
'compare' => 'EXIST'
);
return $meta_query;
};
Run Code Online (Sandbox Code Playgroud)
I've two products:
the_value_2the_valueSo I'm expecting these two products here. When I remove the second meta_query I'm getting only product B.
您可以使用挂钩在过滤器挂钩中的自定义函数woocommerce_product_query_meta_query,您将_the_meta_key在下面的代码中将其替换为您的目标meta_key:
add_filter( 'woocommerce_product_query_meta_query', 'show_only_products_with_specific_metakey', 10, 2 );
function show_only_products_with_specific_metakey( $meta_query, $query ) {
// Only on shop pages
if( ! is_shop() ) return $meta_query;
$meta_query[] = array(
'key' => '_the_meta_key',
'compare' => 'EXISTS'
);
return $meta_query;
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并工作。
添加(与您最后的评论相关):
要使其适用于多个元值,您需要使用'compare' => 'IN',例如:
add_filter( 'woocommerce_product_query_meta_query', 'show_only_products_with_specific_metakey', 10, 2 );
function show_only_products_with_specific_metakey( $meta_query, $query ) {
// Only on shop pages
if( ! is_shop() ) return $meta_query;
$meta_query[] = array(
'key' => '_the_meta_key',
'value' => array('L','XL'),
'compare' => 'IN'
);
return $meta_query;
}
Run Code Online (Sandbox Code Playgroud)
代码位于活动子主题(或活动主题)的 function.php 文件中。经过测试并工作。
| 归档时间: |
|
| 查看次数: |
6968 次 |
| 最近记录: |