Home > WooCommerce > Docs > How to Create A Plugin For WooCommerce

How to Create A Plugin For WooCommerce

Last updated: August 01, 2024
Written and researched by experts at AvadaLearn more about our methodology

By Sam Nguyen

CEO Avada Commerce

WooCommerce plugins, like all others, are based on the WordPress platform. Since WordPress extensions are similar to WooCommerce plugins, anybody familiar with WordPress extension development should have no problem creating one. A developer may utilize and expand the WooCommerce capabilities to create solutions for online merchants, which is the sole distinction.

If you are seeking the best way to develop your own customized WooCommerce plugin, this article is for you. In the next 15 minutes, we will be guiding you through How to create a WooCommerce plugin for your online store along with several outstanding platforms to sell it. Keep reading to find out more!

Why should you create a WooCommerce plugin for your own?

As a WooCommerce user, you are likely to wish to customize the default WooCommerce plugin in order to better fit your needs and desires for your website or store. Also, writing a plugin helps us to keep track of our custom code and make WooCommerce updates a lot easier.

Therefore, we tend to go for the simplest answers, which might lead us to alter the fundamental files of the system. The great thing about WooCommerce is their action hooks, filters, template files - which all enable store owners to modify the files in any way they want. In this way, the whole process of creating your own WooCommerce plugin will become much easier.

Best practices before creating a custom WooCommerce plugin

Because WordPress is a free and open-source platform, it has a wide range of customization options. As a consequence, developers may now create plugins in a variety of methods. If you want to provide your customers a smooth experience when they install your plugin, below is the list of 6 basic principles you should follow:

Proper naming convention

All of your files, classes, methods, and variables should be named after your plugin. If you want to prevent conflicts and misunderstanding with other plugins and themes, use prefixes for all of your functions and variables, just like our example here:

my_plugin_some_function(), my_plugin_my_variable.

Avoid custom database tables

Because WooCommerce has a wide range of built-in database tables, it is strongly suggested that you avoid constructing your own custom database tables. Post types, options, and taxonomies may all be accessed using WooCommerce’s database tables.

Single objective

Object-oriented programming aims to decompose a huge issue into a series of smaller ones. If a function does too much, it’s difficult to grasp its logic, making it more difficult to correct issues. It’s better to break down a large task into smaller ones. For this reason, you should avoid making use of God Objects as much as possible.

Using a Header

A header comment should be at the top of the main PHP file that notifies WooCommerce that the file is a plugin and offers more information about it. The plugin’s file headers appear one per line at the top of the file. HTML code Elements and HTML Tags cannot be included in the header values. Check out our example below:

<?php
/*
Plugin Name: Avada Plugin
Plugin URI:
Description: 
author: sam
Version:
Author URI: 
License: 
*/

WooCommerce Admin Panel

If you are designing the plugin for your own shop or for other merchants, user-experience is a critical factor in the success of the plugin. Your extension’s admin panel must provide a really immersive experience for the merchant when they utilize it. Plus, ensure that all of the buttons have clear, legible text and labels, and a responsive design incorporates these elements.

You can add another security layer by using the current_user_can( string $capability, mixed $args ) function, preventing unauthorized individuals from accessing data. For instance, you may only want the plugin administrator to see a link that was generated by the plugin:

<?php if( current_user_can( ‘manage_links’ ) ) : ?>
     <a href=’#’>My custom plugin link in WP admin</a>
<?php endif ?>

The “manage_links” action is only available to a site administrator by default. For non-administrator users, the preceding snippet will restrict access.

Extensible approach

Users should not have to touch the plugin’s core codebase in order to make modifications or customizations to the plugin using WordPress actions and filters. Online merchants may override the plugin’s template files in their theme’s WooCommerce folder if they have a templating engine installed, which is best recommended when it comes to front-end output.

How to create a custom plugin for WooCommerce?

Here comes the most important question of the day - How to create a WooCommerce plugin on your own? The hybrid development technique is used to construct WooCommerce extensions, a blend of PHP and contemporary Javascript. To get the most out of this tutorial, you should have a clear idea of what you want your extension to do for merchants and customers.

Step 1: Identifying important section in PHP file

In the WooCommerce extension’s primary PHP file, crucial information about the plugin is included. Metadata is used by WordPress and WooCommerce for a variety of ecosystem integration tasks. However, to make the best use of WooCommerce Plugin MetaData, there are several requirements you need to fulfill beforehand:

  • For the Author and Developer fields, it is advised that you use your name or the name of your organization.
  • An extension’s WooCommerce marketplace product page URL is included in the Plugin URI field.
  • The Developer URI should include a link to your official website. To speed up the update process, add the Woo field and populate it with an acceptable value. This snippet may be found by browsing to Extensions > All Extensions as a plugin vendor.

A conditional statement checking for WordPress’s ABSPATH constant is highly recommended. This check ensures that your PHP scripts will not be executed directly by the browser. As a result, they can only be used in the WordPress environment:

defined( 'ABSPATH' ) || exit;

Step 2: Setting up the plugin life cycle

Typically, a WooCommerce plugin’s lifespan must include three different stages: Activate, Execute and Deactivate. For this reason, managing the plugin lifetime should be central to your main PHP file, which serves as the primary point of connection between your extension and WooCommerce.

Hooks for activation and deactivation are created in the main PHP code of the WooCommerce extension. When designing a WooCommerce plugin, you may use the appropriate registration method to register these hooks with WordPress:


function my_extension_activate() {
    // Your activation logic goes here.
}
register_activation_hook( __FILE__, 'my_extension_activate' );


function my_extension_deactivate() {
    // Your deactivation logic goes here.
}
register_deactivation_hook( __FILE__, 'my_extension_deactivate' );

Then it’s time to make sure that your source code has been organized properly in order to bring back the best user experience. There are a variety of methods to structure the code of your extension. Code lines may be organized in a variety of ways, but here are some guidelines to keep in mind:

  • The functionality should be contained in classes.
  • Avoid name clashes via prefixing and namespacing.
  • The declarations, assignments, and implementations should all be checked for errors.

Step 3: Confining the functionality via classes

There are numerous different classes to handle some piece of functionality of your extension. But you need at least construct a core class that can handle the setup, initialization, and administration of a single instance of itself. Talking about that, Encapsulating all the functionality in a single class using the singleton technique is a fantastic way to do it. This is how to put it into practice in your PHP file:


if ( ! class_exists( 'My_Extension' ) ) :
 
    /**
     * My Extension core class
     */
    class My_Extension {npm
        /**
         * The single instance of the class.
         */
        protected static $_instance = null;
 
        /**
         * Constructor.
         */
        protected function __construct() {
            // Instantiation logic will go here.
        }
 
        /**
         * Main Extension Instance.
         * Ensures only one instance of the extension is loaded or can be loaded.
         */
        public static function instance() {
            if ( is_null( self::$_instance ) ) {
                self::$_instance = new self();
            }
 
            return self::$_instance;
        }
 
        /**
         * Cloning is forbidden.
         */
        public function __clone() {
            // Override this PHP function to prevent unwanted copies of your instance.
            //   Implement your own error or use `wc_doing_it_wrong()`
        }
 
        /**
         * Unserializing instances of this class is forbidden.
         */
        public function __wakeup() {
            // Override this PHP function to prevent unwanted copies of your instance.
            //   Implement your own error or use `wc_doing_it_wrong()`
        }
    }
endif;

As you can see, the empty constructor has been used for the following reasons:

  • Load the files your class is dependent on by using a setup function.
  • Check to see that WooCommerce and other sibling requirements are installed and running.
  • Begin by invoking the initialization method of your class and its dependencies.

Step 4: Capture and Apply Discount to your product

When building a WooCommerce plugin from the ground up, remembering and applying product discounts is a key consideration. Each user’s discount is shown by the action show_discount, while the custom profile value is saved by the action save_discount:


public function __construct(){
      add_action('edit_user_profile', array( $this, 'show_discount'), 10, 1);
      add_action( 'edit_user_profile_update', array( $this, 'save_discount'), 10, 1 );
}

Continue, the logged-in user’s information may be retrieved using get_user_meta():

public function show_discount($user) {
?>
<table>
  <tr>
    <th>Discount</th>
    <td>
      <input type="number" id="show_discount" name="show_discount" min="0" max="100" value="<?php echo get_user_meta($user->ID, 'show_user_discount', true)  ?>">
    </td>
    <?php
    if ( ! current_user_can( 'edit_user') ) {
    <td>
      <input type="submit" id="submit" name="submit">
    </td>
    ?>
  </tr>
</table>
<?php
}

public function save_discount($user) {

       if ( ! current_user_can( 'edit_user') ) {
           return false;
           }

       if(isset($_POST['show_discount'])) {
           $show_user_discount = $_POST['show_discount'];
           update_user_meta($user, 'show_discount', $show_user_discount);
       }

}

We show the discount to each user in the plugin. However, only if the user has access to their own information can they adjust the discount amount. Moving on, we can illustrate the price by applying woocommerce_product_get_price filter into your folder:


public function __construct(){
      ...
      add_filter( 'woocommerce_product_get_price', array( $this, 'show_dynamic_price' ), 10, 2);
}

To determine the dynamic pricing, a function called show dynamic price takes the discount value of the current user into account:


//Add within the class body
 public function show_dynamic_price($price, $product) {

      $current_user_id = get_current_user_id();
      $discount = floatval(get_user_meta($current_user_id,'show_discount', true));

      if(!empty($discount)) {
            // Discount is a value between 0 to 100 in percentage
            $dynamic_price = $price - (($price * $discount)/100);
            return $dynamic_price;
      }
}

Step 5: Check out the results

Finally, you’ve completed your plugin and it’s ready for use. After all the work is done, the primary plugin will look like this:


/**
 * Plugin Name: My WooCommerce Extension
 * Plugin URI: http://woocommerce.com/products/woocommerce-extension/
 * Description: Your extension's description text.
 * Version: 1.0.0
 * author: sam
 * Author URI: http://yourdomain.com/
 * Developer: Your Name
 * Developer URI: http://yourdomain.com/
 * Text Domain: my-extension
 * Domain Path: /languages
 *
 * Woo: 12345:342928dfsfhsf8429842374wdf4234sfd
 *
 * License: GNU General Public License v3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 */
 
 
defined( 'ABSPATH' ) || exit;
 
/**
 * Activation and deactivation hooks for WordPress
 */
function myPrefix_extension_activate() {
    // Your activation logic goes here.
}
register_activation_hook( __FILE__, 'myPrefix_extension_activate' );
 
function myPrefix_extension_deactivate() {
    // Your deactivation logic goes here.
 
    // Don't forget to:
    // Remove Scheduled Actions
    // Remove Notes in the Admin Inbox
    // Remove Admin Tasks
}
register_deactivation_hook( __FILE__, 'myPrefix_extension_deactivate' );
 
 
if ( ! class_exists( 'My_Extension' ) ) :
    /**
     * My Extension core class
     */
    class My_Extension {
 
        /**
         * The single instance of the class.
         */
        protected static $_instance = null;
 
        /**
         * Constructor.
         */
        protected function __construct() {
            $this->includes();
            $this->init();
        }
 
        /**
         * Main Extension Instance.
         */
        public static function instance() {
            if ( is_null( self::$_instance ) ) {
                self::$_instance = new self();
            }
            return self::$_instance;
        }
 
        /**
         * Cloning is forbidden.
         */
        public function __clone() {
            // Override this PHP function to prevent unwanted copies of your instance.
            //   Implement your own error or use `wc_doing_it_wrong()`
        }
 
        /**
        

Top 5 platform to sell your custom WooCommerce plugins

Following the development of the plugin, you need a sufficient number of WordPress users to install it on their sites. Creating a website and promoting it to attract your target audience are the next steps. Launching your plugin in an established marketplace that already has a large user base is the next best option for getting your audience the exposure it requires.

If you are looking for the perfect marketplace, don’t miss out on our list on top 5 platforms to sell your custom WooCommerce plugins:

CodeCanyon

CodeCanyon

Envato’s CodeCanyon is a popular marketplace. Differ from WordPress.org, this is a location where you can sell your plugin for a reasonable fee without creating an extra freemium version. Also, You don’t have to go through the painstaking process of selling a plugin in order to reach a large audience of WordPress devotees.

WordPress Plugin Directory

WordPress Plugin Directory

Up to the present, WordPress Plugin Directory is one of the most popular marketplace among online store owners. As long as your themes and plugins are free, you may submit them to WordPress.org for evaluation and have them published. You’ll receive a lot of downloads because of the large distribution you get through their site.

Another great thing about Wordpress is that you will gain access to plugin statistics (downloads and active installations), a help forum, a changelog, and many more without paying any fees. Additionally, selling plugins on WordPress also helps you to reach more customers and directly receive feedback from them on the platform.

WooCommerce Marketplace

WooCommerce Marketplace

Because you are designing a customized WooCommerce plugin, what would be better than uploading your creation onto the WooCommerce Marketplace?

All of your logistical, technological, and marketing demands may be met with thousands of free and paid WooCommerce extensions. In the WooCommerce marketplace, you may earn up to 70% of the Product Net Revenue by selling your plugin. Addition to those, you’ll be able to get in front of those who only use WooCommerce when your plugin is sold on WooCommerce Marketplace.

ThemeForest

ThemeForest

ThemeForest by Envato is another marketplace you can not skip through. More than 40,000 themes and templates have been released on Themeforest by more than 3,00 writers since its launch in 2010.

As a Themeforest exclusive seller, you’ll earn 62.5 percent of each sale of your items. As your overall sales improve, your commissions do, too. 87.50 percent of each sale will be yours if you hit $75,000 in total sales on their site. 45 percent of the money goes to non-exclusive writers.

There is a lot of traffic on this page, so you’ll be able to get your first few sales off the ground. However, it’s not a guarantee that you’ll make a lot of money just by being listed here. If you want to get in, you’re going to have to put a lot of effort into making a high-quality theme.

Mojo Marketplace

Mojo Marketplace

While not as popular as Themeforest, Mojo Marketplace’s integration with hosting services like HostGator is a major selling point for the service. Because of this, a large number of brand-new WordPress users will discover your themes and plugins while building their site.

Exclusive writers may expect to earn 50-70 percent on commissions from Mojo Marketplace. All sales made by non-exclusive writers are split 50/50.

Conclusion

To sum up, we hope that our guide on How to create a WooCommerce plugin on your own has solved your questions related to the topic. After all, this feature gives you the ability not only to update your online store the way you want but also earn you more money. Feel free to show your results in the comments section below!


Sam Nguyen is the CEO and founder of Avada Commerce, an e-commerce solution provider headquartered in Singapore. He is an expert on the Shopify e-commerce platform for online stores and retail point-of-sale systems. Sam loves talking about e-commerce and he aims to help over a million online businesses grow and thrive.

Stay in the know

Get special offers on the latest news from AVADA.