Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding WooCommerce Attribute via PHP code

I could see a lots of question on adding woocommerce product attribute. But doing so, I could see those added attributes in this screen

wp-admin/edit.php?post_type=product&page=product_attributes

My question is how can we add the attributes via PHP code to so that it appears in this above specified woocommerce attribute screen ? My intention is to make these attributes visible under 'Layered Navs' widget to filter out.

like image 951
James Hayes Avatar asked Jun 22 '26 14:06

James Hayes


1 Answers

Following code will create the attribute programmatically which will be visible on the product_attributes page in the backend.

        global $wpdb; 

        $insert = $wpdb->insert(
            $wpdb->prefix . 'woocommerce_attribute_taxonomies',
            array(
                'attribute_label'   => 'name',
                'attribute_name'    => 'slug',
                'attribute_type'    => 'type',
                'attribute_orderby' => 'order_by',
                'attribute_public'  => 1
            ),
            array( '%s', '%s', '%s', '%s', '%d' )
        );

        if ( is_wp_error( $insert ) ) {
            throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 );
        }

        // Clear transients
        delete_transient( 'wc_attribute_taxonomies' );

Change name, slug etc with the relevant values.

like image 135
Anand Shah Avatar answered Jun 24 '26 23:06

Anand Shah