[英]Get all WooCommerce products from a category that have specific meta data
I have a custom meta on my custom post type:我的自定义帖子类型有一个自定义元数据:
$arr = array('foo' => 'yes',
'featured_enabled' => 123,
'something' => 'abc',
);
update_post_meta($post_id, 'fvp_featured_meta', $arr );
My question is how can I get all products from specific category ID in woocommerce that have this meta (fvp_featured_meta)?我的问题是如何从 woocommerce 中的特定类别 ID 中获取具有此元数据 (fvp_featured_meta) 的所有产品? (not all posts have this meta) (并非所有帖子都有这个元)
You can try to use wc_get_products()
function to get products that have a specific meta data belonging to a specific product category as follows:您可以尝试使用wc_get_products()
函数来获取具有属于特定产品类别的特定元数据的产品,如下所示:
$category_term_slugs = array('clothing'); // <== Define your product category
// Get an array of WC_Product Objects
$products = wc_get_products( array(
'limit' => -1,
'status' => 'publish',
'meta_key' => 'fvp_featured_meta',
'meta_compare' => 'EXISTS',
'category' => $category_term_slugs,
) );
echo '<ul>';
// Loop Through products array
foreach( $products as $product ) {
$product_name = $product->get_name();
$meta_array = $product->get_meta('fvp_featured_meta'); // Get meta data (array)
$meta_output = []; // Initializing
if( ! empty( $meta_array ) ) {
// Loop through custom field array key/value pairs
foreach( $meta_array as $key => $value ) {
$meta_output[] = $key . ': ' . $value;
}
$meta_output = ' | ' . implode(' | ', $meta_output);
}
echo '<li>' . $product_name . $meta_output . '</li>';
}
echo '</ul>';
It should works.它应该有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.