Reputation: 93
In WooCommerce I am trying to add a custom field to all of product attributes as a plugin…
For the moment in the code below, I am able to add a custom field to one taxonomy:
function pippin_taxonomy_add_new_meta_field() {
// this will add the custom meta field to the add new term page
?>
<div class="form-field">
<label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'pippin' ); ?></label>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="">
<p class="description"><?php _e( 'Enter a value for this field','pippin' ); ?></p>
</div>
<?php
}
add_action( 'pa_flavor_add_form_fields', 'pippin_taxonomy_add_new_meta_field', 10, 2 );
// Edit term page
function pippin_taxonomy_edit_meta_field($term) {
// put the term ID into a variable
$t_id = $term->term_id;
// retrieve the existing value(s) for this meta field. This returns an array
$term_meta = get_option( "taxonomy_$t_id" ); ?>
<tr class="form-field">
<th scope="row" valign="top"><label for="term_meta[custom_term_meta]"><?php _e( 'Example meta field', 'pippin' ); ?></label></th>
<td>
<input type="text" name="term_meta[custom_term_meta]" id="term_meta[custom_term_meta]" value="<?php echo esc_attr( $term_meta['custom_term_meta'] ) ? esc_attr( $term_meta['custom_term_meta'] ) : ''; ?>">
<p class="description"><?php _e( 'Enter a value for this field','pippin' ); ?></p>
</td>
</tr>
<?php
}
add_action( 'pa_flavor_edit_form_fields', 'pippin_taxonomy_edit_meta_field', 10, 2 );
How to get all WooCommerce product attributes taxonomies slugs (and names)?
This way I could make those custom fields dynamically for all existing product attributes.
Upvotes: 5
Views: 9679
Reputation: 253784
You can get product attribute taxonomy slugs (and taxonomy names) by using:
Before WooCommerce version 3.6 with wc_get_attribute_taxonomies()
dedicated function:
// Get an array of product attribute taxonomies slugs
$attributes_tax_slugs = array_keys( wp_list_pluck( wc_get_attribute_taxonomies(), 'attribute_label', 'attribute_name' ) );
// Get an array of product attribute taxonomies names (starting with "pa_")
$attributes_tax_names = array_filter( array_map( 'wc_attribute_taxonomy_name', $attribute_taxonomies ));
Since WooCommerce version 3.6+ with wc_get_attribute_taxonomy_labels()
dedicated function:
// Get an array of product attribute taxonomies slugs
$attributes_tax_slugs = array_keys( wc_get_attribute_taxonomy_labels() );
// Get an array of product attribute taxonomies names (starting with "pa_")
$attributes_tax_names = array_filter( array_map( 'wc_attribute_taxonomy_name', $attribute_taxonomies ));
Official documentation:
wc-attribute-functions.php
core filewp_list_pluck()
functionarray_keys()
, array_filter()
and array_map()
Upvotes: 13