Create attributes in WooCommerce programmatically

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

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

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

You can also go through creating a WooCommerce product attribute lookup table.

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

You can also check out our WooCommerce plugin which can help you achieve most of the features and functionality you need.

Attributes are important for:

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

Now that we have a better understanding of attributes, let’s take a look at how to add product attributes to WooCommerce.

Step 1: Create a custom plugin

First of all, create a directory for your new WooCommerce plugin in the plugin 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 like.

Then open this folder in your favorite text editor and create a php file like ”wkwc-add-custom-atrributes.php”.

You can check more about managing product taxonomies and filtering products by attributes for better understanding.

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

/**
 * 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 information.

Step 2: Add the following code to the main plugin 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’ve added the code to the main plugin file, save the file and activate the plugin in your 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.

The 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 an attribute to the product.

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

The product editor page where we can add an attribute to a product.

Step 5: WooCommerce front view

On the front end, you can see the product attributes on a single product’s WooCommerce page. This is a screenshot of your custom product attribute on a single product WooCommerce page:

Woocommerce page of one product.

That’s all about “How to Create Attributes in Woocommerce”. Happy coding!

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

Additionally, you can also hire WooCommerce developers for your next project.

Source link

Leave a Reply

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