Create new product attribute programmatically in W

2019-01-11 21:01发布

问题:

How can I create attributes for WooCommerce from a plugin? I find only :

wp_set_object_terms( $object_id, $terms, $taxonomy, $append);

From this stack-question

But this approach required id of some product. I need to generate some attributes not attached to any products.

回答1:

To create a term you can use wp_insert_term()

like so:

wp_insert_term( 'red', 'pa_colors' );

where colors is the name of your attribute. The taxonomy name of an attribute is always prepended by pa_.

Edit Attributes are merely custom taxonomies. Or you could say they are dynamic taxonomies that are manually created by the user in the back-end. Still all the same custom taxonomy rules apply.

You can see the source code here which loops through the attributes and runs register_taxonomy() on each. So to create a new attribute (remember it is just a taxonomy) then you need to run register_taxonomy() and simple prepend pa_ to the start of the taxonomy name.

Mimicking some of the values of the taxonomy args from core, would get you something like this for a 'Colors' attribute.

add_action( 'woocommerce_after_register_taxonomy', 'so_29549525_register_attribute' );

function so_29549525_register_attribute(){

    $permalinks = get_option( 'woocommerce_permalinks' );

    $taxonomy_data = array(
                        'hierarchical'          => true,
                        'update_count_callback' => '_update_post_term_count',
                        'labels'                => array(
                                'name'              => 'Colors',
                                'singular_name'     => 'Color',
                                'search_items'      => sprintf( __( 'Search %s', 'woocommerce' ), $label ),
                                'all_items'         => sprintf( __( 'All %s', 'woocommerce' ), $label ),
                                'parent_item'       => sprintf( __( 'Parent %s', 'woocommerce' ), $label ),
                                'parent_item_colon' => sprintf( __( 'Parent %s:', 'woocommerce' ), $label ),
                                'edit_item'         => sprintf( __( 'Edit %s', 'woocommerce' ), $label ),
                                'update_item'       => sprintf( __( 'Update %s', 'woocommerce' ), $label ),
                                'add_new_item'      => sprintf( __( 'Add New %s', 'woocommerce' ), $label ),
                                'new_item_name'     => sprintf( __( 'New %s', 'woocommerce' ), $label )
                            ),
                        'show_ui'           => false,
                        'query_var'         => true,
                        'rewrite'           => array(
                            'slug'         => empty( $permalinks['attribute_base'] ) ? '' : trailingslashit( $permalinks['attribute_base'] ) . sanitize_title( 'colors' ),
                            'with_front'   => false,
                            'hierarchical' => true
                        ),
                        'sort'              => false,
                        'public'            => true,
                        'show_in_nav_menus' => false,
                        'capabilities'      => array(
                            'manage_terms' => 'manage_product_terms',
                            'edit_terms'   => 'edit_product_terms',
                            'delete_terms' => 'delete_product_terms',
                            'assign_terms' => 'assign_product_terms',
                        )
                    );

    register_taxonomy( 'pa_colors', array( 'product' ) ), $taxonomy_data );

}


回答2:

For Woocommerce 3+ (2018)

To create a new product attribute from a label name use the following function:

function create_product_attribute( $label_name ){
    global $wpdb;

    $slug = sanitize_title( $label_name );

    if ( strlen( $slug ) >= 28 ) {
        return new WP_Error( 'invalid_product_attribute_slug_too_long', sprintf( __( 'Name "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
    } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) {
        return new WP_Error( 'invalid_product_attribute_slug_reserved_name', sprintf( __( 'Name "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), array( 'status' => 400 ) );
    } elseif ( taxonomy_exists( wc_attribute_taxonomy_name( $label_name ) ) ) {
        return new WP_Error( 'invalid_product_attribute_slug_already_exists', sprintf( __( 'Name "%s" is already in use. Change it, please.', 'woocommerce' ), $label_name ), array( 'status' => 400 ) );
    }

    $data = array(
        'attribute_label'   => $label_name,
        'attribute_name'    => $slug,
        'attribute_type'    => 'select',
        'attribute_orderby' => 'menu_order',
        'attribute_public'  => 0, // Enable archives ==> true (or 1)
    );

    $results = $wpdb->insert( "{$wpdb->prefix}woocommerce_attribute_taxonomies", $data );

    if ( is_wp_error( $results ) ) {
        return new WP_Error( 'cannot_create_attribute', $results->get_error_message(), array( 'status' => 400 ) );
    }

    $id = $wpdb->insert_id;

    do_action('woocommerce_attribute_added', $id, $data);

    wp_schedule_single_event( time(), 'woocommerce_flush_rewrite_rules' );

    delete_transient('wc_attribute_taxonomies');
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.


Based on:

  • Product Attribute wc_create_attribute() function code (Woocommerce 3.2+).
  • Create programmatically a variable product and two new attributes in Woocommerce