This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Populate products field using SKUs from ACF field | |
* Create an ACF field with the name child_product_skus | |
* Enter the SKUs of the child products into this field as a comma-separated list | |
*/ | |
function prefix_populate_products_through_ACF( $item, $group, $group_id, $post_id ) { | |
// Check ACF is active | |
if( ! function_exists( 'get_field' ) ) { | |
return $item; | |
} | |
$skus = get_field( 'child_product_skus', $post_id ); | |
// Bounce if this field or product doesn't apply | |
if( ! $skus || empty( $item['field_type'] ) || $item['field_type'] != 'products' ) { | |
return $item; | |
} | |
// Split the list of SKUs into an array | |
$skus = explode( ',', $skus ); | |
$child_products = array(); | |
// Iterate through each SKU and find the child product ID | |
foreach( $skus as $sku ) { | |
// Add the child product ID | |
$child_products[] = wc_get_product_id_by_sku( trim( $sku ) ); | |
} | |
// Populate the child products for this product | |
$item['child_products'] = $child_products; | |
return $item; | |
} | |
add_filter( 'pewc_filter_item_start_list', 'prefix_populate_products_through_ACF', 10, 4 ); | |
/** | |
* Filter add-on groups ensuring that a specific group is included if the product has the child_product_skus ACF field | |
* Edit the group ID in $global_group_id below. | |
*/ | |
function prefix_filter_groups_by_ACF( $groups, $product_id ) { | |
// Update this to the ID of the global group you would like to insert into products automatically | |
$global_group_id = 72; | |
// Check ACF is active | |
if( ! function_exists( 'get_field' ) ) { | |
return $groups; | |
} | |
$skus = get_field( 'child_product_skus', $product_id ); | |
// Bounce if this field is empty | |
if( ! $skus ) { | |
return $groups; | |
} | |
$global_group = pewc_get_group_fields( $global_group_id ); | |
$groups[$global_group_id]['items'] = $global_group; | |
return $groups; | |
} | |
add_filter( 'pewc_filter_product_extra_groups', 'prefix_filter_groups_by_ACF', 10, 2 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment