I'm working on a plugin to import variable products on woocommerce.
I'm trying to create attributes to work with. So, I use this function to create the taxonomies
process_add_attribute(array('attribute_name' => 'color', 'attribute_label' => 'Color', 'attribute_type' => 'text', 'attribute_orderby' => 'menu_order', 'attribute_public' => false));
function process_add_attribute($attribute)
{
global $wpdb;
// check_admin_referer( 'woocommerce-add-new_attribute' );
if (empty($attribute['attribute_type'])) { $attribute['attribute_type'] = 'text';}
if (empty($attribute['attribute_orderby'])) { $attribute['attribute_orderby'] = 'menu_order';}
if (empty($attribute['attribute_public'])) { $attribute['attribute_public'] = 0;}
if ( empty( $attribute['attribute_name'] ) || empty( $attribute['attribute_label'] ) ) {
return new WP_Error( 'error', __( 'Please, provide an attribute name and slug.', 'woocommerce' ) );
} elseif ( ( $valid_attribute_name = valid_attribute_name( $attribute['attribute_name'] ) ) && is_wp_error( $valid_attribute_name ) ) {
return $valid_attribute_name;
} elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $attribute['attribute_name'] ) ) ) {
return new WP_Error( 'error', sprintf( __( 'Slug "%s" is already in use. Change it, please.', 'woocommerce' ), sanitize_title( $attribute['attribute_name'] ) ) );
}
$wpdb->insert( $wpdb->prefix . 'woocommerce_attribute_taxonomies', $attribute );
do_action( 'woocommerce_attribute_added', $wpdb->insert_id, $attribute );
flush_rewrite_rules();
delete_transient( 'wc_attribute_taxonomies' );
return true;
}
This creates the taxonomies and I can see them in Products->Attributes. But if I create a script that first creates the taxonomies and them try to add a term to them (working with parent product) using:
$var test = wp_set_post_terms($post_id, $avail_color, 'pa_color', true);
where $post_id is the id of the recently created product post, $avail_color is an array with {'red','blue'} and 'pa_color' is the name of the created taxonomy.
First time I run it text gives me invalid taxonomy error. But if I run it twice it works well and insert the terms into the pa_color taxonomy. (Notice that second time the script runs the tax is not created because it already exits).
I'm thinking about some kind of flush that must be done but I can't find how to fix it...