Book Image

WooCommerce Cookbook

By : Patrick Rauland
Book Image

WooCommerce Cookbook

By: Patrick Rauland

Overview of this book

Table of Contents (17 chapters)
WooCommerce Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a WooCommerce plugin


Unlike a lot of hosted e-commerce solutions, WooCommerce is entirely customizable. That's one of the huge advantages for anyone who builds on open source software. If you don't like it, you can change it. At some point, you'll probably want to change something that's not on a settings page, and that's when you may want to dig into the code. Even if you don't know how to code, you may want to look this over so that when you work with a developer, you would know they're doing it the right way.

Getting ready

In addition to having admin access to a WordPress site, you'll also need FTP credentials so you can upload a plugin. You'll also need a text editor. Popular code editors include Sublime Text, Coda, Dreamweaver, and Atom. I personally use Atom. You could also use Notepad on a Windows machine or Text Edit on a Mac in a pinch.

How to do it…

We're going to be creating a plugin that interacts with WooCommerce. It will take the existing WooCommerce functionality and change it. These are the WooCommerce basics. If you build a plugin like this correctly, when WooCommerce isn't active, it won't do anything at all and won't slow down your website. Let's create a plugin by performing the following steps:

  1. Open your text editor and create a new file. Save the file as woocommerce-demo-plugin.php.

  2. In that file, add the opening PHP tag, which looks like this: <?php.

  3. On the next line, add a plugin header. This allows WordPress to recognize the file as a plugin so that it can be activated. It looks something like the following:

    /**
     * Plugin Name: WooCommerce Demo Plugin
     * Plugin URI: https://gist.github.com/BFTrick/3ab411e7cec43eff9769
     * Description: A WooCommerce demo plugin
     * Author: Patrick Rauland
     * Author URI: http://speakinginbytes.com/
     * Version: 1.0
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU General Public License as published by
     * the Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
     * GNU General Public License for more details.
     *
     * You should have received a copy of the GNU General Public License
     * along with this program. If not, see <http://www.gnu.org/licenses/>.
     *
     */
  4. Now that WordPress knows that your file is a plugin, it's time to add some functionality to this. The first thing a good developer does is makes sure their plugin won't conflict with another plugin. To do that, we make sure an existing class doesn't have the same name as our class. I'll be using the WC_Demo_Plugin class, but you can use any class name you want. Add the following code beneath the plugin header:

    if ( class_exists( 'WC_Demo_Plugin' ) ) { 
        return;
    }
    
    class WC_Demo_Plugin { 
    
    } 
  5. Our class doesn't do anything yet, but at least we've written it in such a way that it won't break another plugin. There's another good practice we should add to our plugin before we add the functionality, and that's some logic to make sure another plugin won't misuse our plugin. In the vast majority of use cases, you want to make sure there can't be two instances of your code running. In computer science, this is called the Singleton pattern. This can be controlled by tracking the instances of the plugin with a variable. Right after the WC_Demo_Plugin { line, add the following:

    protected static $instance = null;
    
    
    /**
     * Return an instance of this class.
     *
     * @return object A single instance of this class.
     * @since  1.0
     */
    public static function get_instance() {
        // If the single instance hasn't been set, set it now.
        if ( null == self::$instance ) {
            self::$instance = new self;
        }
    
        return self::$instance;
    }

    And get the plugin started by adding this right before the endif; line:

    add_action( 'plugins_loaded', array( 'WC_Demo_Plugin', 'get_instance' ), 0 );
  6. At this point, we've made sure our plugin doesn't break other plugins and we've also dummy-proofed our own plugin so that we or other developers don't misuse it. Let's add just a bit more logic so that we don't run our logic unless WooCommerce is already loaded. This will make sure that we don't accidentally break something if we turn WooCommerce off temporarily. Right after the protected static $instance = null; line, add the following:

    /**
     * Initialize the plugin.
     *
     * @since 1.0
     */
    private function __construct() {
        if ( class_exists( 'WooCommerce' ) ) {
    
        }
    }
  7. And now our plugin only runs when WooCommerce is loaded. I'm guessing that at this point, you finally want it to do something, right? After we make sure WooCommerce is running, let's add some functionality. Right after the if ( class_exists( 'WooCommerce' ) ) { line, add the following code so that we add an admin notice:

    // print an admin notice to the screen.
    add_action( 'admin_notices', array( $this, 'my_admin_notice' ) );

    This code will call a method called my_admin_notice, but we haven't written that yet, so it's not doing anything. Let's write that method. Have a look at the __construct method, which should now look like this:

    /**
     * Initialize the plugin.
     *
     * @since 1.0
     */
    private function __construct() {
        if ( class_exists( 'WooCommerce' ) ) {
    
            // print an admin notice to the screen.
            add_action( 'admin_notices', array( $this, 'display_admin_notice' ) );
    
        }
    } 

    Add the following after the preceding __construct method:

    /**
     * Print an admin notice
     *
     * @since 1.0
     */
    public function display_admin_notice() {
        ?>
        <div class="updated">
            <p><?php _e( 'The WooCommerce dummy plugin notice.', 'woocommerce-demo-plugin' ); ?></p>
        </div>
        <?php
    }

    This will print an admin notice on every single admin page. This notice includes all the messages you typically see in the WordPress admin. You could replace this admin notice method with just about any other hook in WooCommerce to provide additional customizations in other areas of WooCommerce, whether it be for shipping, the product page, the checkout process, or any other area. This plugin is the easiest way to get started with WooCommerce customizations.

    Note

    If you'd like to see the full code sample, you can see it at https://gist.github.com/BFTrick/3ab411e7cec43eff9769.

  8. Now that the plugin is complete, you need to upload it to your plugins folder. You can do this via the WordPress admin or more commonly via FTP.

  9. Once the plugin has been uploaded to your site, you'll need to activate the plugin just like any other WordPress plugin. The end result is a notice in the WordPress admin letting us know we did everything successfully.

Note

Whenever possible, use object-oriented code. That means using objects (like the WC_Demo_Plugin class) to encapsulate your code. It will prevent a lot of naming conflicts down the road. If you see some procedural code online, you can usually convert it to object-oriented code pretty easily. Object-oriented programming is out of the scope of this book, but you can read more at http://codex.wordpress.org/Plugin_API.