3

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Hi,This snippet works as fine. But it failed to work on the activation hook of the plugin. I have to create few product attributes on plugin activation. What is the solution? I do not find any issue on running this code after the page is loaded.
Which hook have to attached the code to? Please note there's no guarantee that WooCommerce will always load before your plugin. Try running the code on woocommerce_loaded
Preferably on plugin activation hook. In that way, I can define few woocommerce product attributes.
ah yes certainly, forgot about it. Thanks for pointing it out have updated the code for future visitors.
Happy to know that your code worked fine. I have few custom requirements. Would you able to do for a small fee? It is related with setting a AJAX styled product search form and showing results on pagination. And few more requirements.....
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.