I have products to insert from an API, after many search I was able to create the attribute using the following code (ie memory):

// Insert new attribute
function process_add_attribute($attribute) {
    global $wpdb;

    if (empty($attribute['attribute_type'])) { 
        $attribute['attribute_type'] = 'select'; 
    }
    if (empty($attribute['attribute_orderby'])) { 
        $attribute['attribute_orderby'] = 'name'; 
    }
    if (empty($attribute['attribute_public'])) { 
        $attribute['attribute_public'] = 1; 
    }

    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;
    }

    $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;
}

function valid_attribute_name( $attribute_name ) {
    if ( strlen( $attribute_name ) >= 28 ) {
            return new WP_Error( 'error', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
    } elseif ( wc_check_if_attribute_name_is_reserved( $attribute_name ) ) {
            return new WP_Error( 'error', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), sanitize_title( $attribute_name ) ) );
    }

    return true;
}

Now I need to insert a term for the created attribute, when I try this pieace of code in the same script, term is not added (ex 4GB):

// Insert term to the attribute
wp_insert_term(
    $value,
    'pa_' . $sanitized_label,
    array(
        'description' => $value,
        'slug'    => $sanitized_value
    )
);

If I re run the script, becuase the attribute is added the term now added successfully. I need to add the term after creating the attribute directyl.

I have tried add_hook to use some callback, no lucl :

// add the action 
add_action( 'woocommerce_attribute_added', 'action_woocommerce_attribute_added', 10, 3 ); 

function action_woocommerce_attribute_added( $array, $int, $int ) { 
    // Insert term to the attribute
    wp_insert_term(
        '4gb',
        'pa_memory',
        array(
            'description' => '4gb',
            'slug'    => '4gb'
        )
    );
}

Read more here: WordPress/Woocommerce – add term after adding attribute directly


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: