I was working on a project recently where the need arose to add a custom image to be associated with a specific WooCommerce attribute.
This handy little snippet will do just that! I used Advanced Custom Fields (ACF) and thus wanted a solution that would integrate with it.
<?php | |
// Adds a custom rule type. | |
add_filter( 'acf/location/rule_types', function( $choices ){ | |
$choices[ __("Other",'acf') ]['wc_prod_attr'] = 'WC Product Attribute'; | |
return $choices; | |
} ); | |
// Adds custom rule values. | |
add_filter( 'acf/location/rule_values/wc_prod_attr', function( $choices ){ | |
foreach ( wc_get_attribute_taxonomies() as $attr ) { | |
$pa_name = wc_attribute_taxonomy_name( $attr->attribute_name ); | |
$choices[ $pa_name ] = $attr->attribute_label; | |
} | |
return $choices; | |
} ); | |
// Matching the custom rule. | |
add_filter( 'acf/location/rule_match/wc_prod_attr', function( $match, $rule, $options ){ | |
if ( isset( $options['taxonomy'] ) ) { | |
if ( '==' === $rule['operator'] ) { | |
$match = $rule['value'] === $options['taxonomy']; | |
} elseif ( '!=' === $rule['operator'] ) { | |
$match = $rule['value'] !== $options['taxonomy']; | |
} | |
} | |
return $match; | |
}, 10, 3 ); |
First, add the snippet above to your themes functions.php
Next, add a new Field Group using ACF. You will see a new option to select a WC Product Attribute. Assign it to the WooCommerce Attribute of your choice and add your custom fields as normal.
And that’s it! Now you can visit the Product Attributes and you will see the custom fields that you’ve added to the new Field Group.
I hope this helps you like it helped me! If you got value out of this article, share it on your socials! 🙂
Leave a Reply