让分配给分组产品的所有单一产品在存档/类别页面上可用并可见并不是一个理想的解决方案,我想知道如何解决这个问题。
我知道 WooCommerce 中有一个“可见性”选项,但这更不理想。
据我了解,WooCommerce 现在使用
meta data
而不是 post_parent
,因此,我寻求帮助以了解如何更新此查询以涵盖这一点。
我尝试过但不再起作用的代码来自这里:
add_action( 'woocommerce_product_query', 'hide_single_products_assigned_to_grouped_product_from_archive' );
function hide_single_products_assigned_to_grouped_product_from_archive( $q ){
$q->set( 'post_parent', 0 );
}
您无法真正定位产品查询中分组产品中的子产品,因为数据作为序列化数组存储在
_children
表上的 wp_post_meta
meta_key 下。
但是您可以做的是首先向分组产品中的所有子产品添加自定义字段。然后您将能够使用该自定义字段来更改产品查询。
以下函数将完成该工作,并且您将运行它仅一次:
function add_a_custom_field_to_grouped_children_products() {
// get all grouped products Ids
$grouped_ids = wc_get_products( array( 'limit' => -1, 'type' => 'grouped', 'return' =>'ids' ) );
// Loop through grouped products
foreach( $grouped_ids as $grouped_id ){
// Get the children products ids
$children_ids = (array) get_post_meta( $grouped_id, '_children', true );
// Loop through children product Ids
foreach( $children_ids as $child_id ) {
// add a specific custom field to each child with the parent grouped product id
update_post_meta( $child_id, '_child_of', $grouped_id );
}
}
}
add_a_custom_field_to_grouped_children_products(); // Run the function
代码位于活动子主题(或活动主题)的functions.php 文件中。
保存后,浏览您网站的任何页面。然后删除该代码并保存。
现在您所有分组的儿童产品都将有一个自定义字段。如果您添加/创建更多分组产品,您将需要以下功能来将该自定义字段添加到子产品中:
// Add on the children products from a grouped product a custom field
add_action( 'woocommerce_process_product_meta_grouped', 'wc_action_process_children_product_meta' );
function wc_action_process_children_product_meta( $post_id ) {
// Get the children products ids
$children_ids = (array) get_post_meta( $post_id, '_children', true );
// Loop through children product Ids
foreach( $children_ids as $child_id ) {
// add a specific custom field to each child with the parent grouped product id
update_post_meta( $child_id, '_child_of', $post_id );
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。
现在完成,将在所有产品上隐藏的功能循环分组产品中的子产品:
add_filter( 'woocommerce_product_query_meta_query', 'hide_children_from_grouped_products' );
function hide_children_from_grouped_products( $meta_query ) {
if( ! is_admin() ) {
$meta_query[] = array(
'key' => '_child_of',
'compare' => 'NOT EXISTS'
);
}
return $meta_query;
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。
我的网站有问题,加载此网站后,我只能查看分组产品的定价,而不能查看简单产品的定价。我已经从网站上删除了所有其他附加代码,并且似乎只能认为这就是原因。