Reading list Switch to dark mode

    How To Create Attributes In WooCommerce Programmatically?

    Updated 12 April 2024

    In this blog, we will see how to create attributes in WooCommerce with coding.

    Before proceeding further we should know what are WooCommerce attributes. In WooCommerce, you can add information to your products through attributes.

    These features depend on the product. For example, common attributes for clothing items are size and color.

    You can also go through the creation of a WooCommerce Product attribute lookup table.

    The interesting thing about attributes is that they are global. Instead of applying them to every product, you simply create them and add them to different products.

    Searching for an experienced
    WordPress Company ?
    Find out More

    You can also check our WooCommerce plugin that can help you achieve most of the required features and functionalities.

    Attributes are essential for:

    • Variable products: Before creating variable products, you have to define attributes for them. This allows you to add variations of the product.
    • Filtering products: A common way of filtering is based on attributes. For example, a user may be looking for a 15-inch screen laptop.

    Now that we have a better understanding of attributes, let’s see how to add product attributes in WooCommerce.

    Step 1: Create a Custom Plugin

    First of all, create a directory for your new WooCommerce plugin in the plugins directory path i.e. ‘/wp-content/plugins/’.

    In my case, the directory name is ‘wkwc-add-custom-atrributes’ you can change your directory name as you want.

    Next, Open this folder in your preferred text editor and create a php file like ‘‘wkwc-add-custom-atrributes.php’.

    You can check more about managing product taxonomies and filter products by attribute for a better understanding.

    Put the following header comments in the PHP file to make this a plugin file.

    /**
     * Plugin Name: WooCommerce Create Attributes
     * Description: This will create a attribute of the product.
     * Author: Webkul
     * Author URI: https://webkul.com/
     * Version: 1.0.0
     * Text Domain: wkwc-attribute
     *
     * @package WooCommerce Create Attributes
     */

    You can change the above information to match your details.

    Step 2: Add the following code to the plugin’s main file.

    // This hook is triggered before any other hook when a user accesses the admin area.
    add_action('admin_init', 'wkwc_add_product_attributes');
    
    function wkwc_add_product_attributes() {
        $atts=array(
            'price' =>array('< 50000','> 50000', '= 50000'),
            'brand' =>array('hp','dell','apple'),
        );
    
        foreach ( $atts as $key => $values ) {
           new Wkwc_Add_Attribute( $key, $values );
        }
    }
    
    /**
     * Add attribute class.
     */
    class Wkwc_Add_Attribute{
    
        /**
    	 * Constructor of this class.
    	 */
        public function __construct( $name, $val ) {
    
    		$attrs = array();
    		$attributes = wc_get_attribute_taxonomies();
    
    		foreach ( $attributes as $key => $value ) {
    			array_push( $attrs,$attributes[$key]->attribute_name );
    		}
    
    		if ( ! in_array( $name, $attrs ) ) {
    			$args = array(
    				'id' => 'wkwc-custom-attribute',
    				'slug'    => $name,
    				'name'   => __( $name, 'wkwc-attribute' ),
    				'type'    => 'select',
    				'orderby' => 'menu_order',
    				'has_archives'  => false,
    				'limit' => 1,
    				'is_in_stock' => 1
    			);
    
    			return wc_create_attribute( $args ); // Create the attribute.
    		}
    
    		$this->wkwc_add_var( $name, $val );
        }
    
    	/**
    	 * Add all variations contained in the original array to the attribute, this is also passed through the function.
    	 *
    	 * @param string $name Attribute name.
    	 * @param string $val Attribute value.
    	 */
    	public function wkwc_add_var( $name, $val ) {
            $taxonomy = 'pa_'.$name;
            $term_slug = sanitize_title($name);
    
            // Check if the term exist and if not it create it (and get the term ID).
            for ($ff=0; $ff < count($val) ; $ff++) {
                if( ! term_exists( $val[$ff], $taxonomy ) ){
    				$term_data = wp_insert_term($val[$ff], $taxonomy );
    				$term_id = $term_data['term_id'];
    			} else {
    				$term_id = get_term_by( 'name', $val[$ff], $taxonomy )->term_id;
    			}
    		}
    	}
    }

    Step 3: Save and activate the plugin

    Once you have added the code to the main plugin file, save the file and activate the plugin in the WordPress admin panel.

    To activate the plugin, go to the “Plugins” menu and find the plugin you just created. Click “Activate” to enable the plugin.

    Installed plugins page where we can see the installed plugins.

    Now, we can see the custom attributes in the Products > Attributes.

    Attributes section where all product attributes are listed.

    Step 4: Add the attribute to a product.

    Additionally, attributes for setting product variations will also be available on the product editor page:

    Product editor page at which we can add the attribute on product.

    Step 5: WooCommerce Front-View

    On the front end, you can view your product attributes on the WooCommerce single product page. Here is the screenshot of your custom product attribute on the WooCommerce single product page:

    Woocommerce single product page.

    That’s all about “How to create attributes in Woocommerce”. Have a nice coding!

    Support

    If you need any technical assistance, please reach us by mail at [email protected].

    Additionally, you can also Hire WooCommerce Developers for your next project.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home

    Table of Content