Doesn't it seem to you that some WordPress plugins are lucky? WooCommerce, Easy Digit Download, Gravity Forms : each of these plugins is powered by an entire company, with dozens of third-party extensions and more and more features added by them that add to the potential of the plugin. During this time, most of the other plugins fail to progress.

How can a single plugin become the basis of a thriving tech ecosystem? There are a lot of answers: be the first to market, create a great product, have marketing acumen, and everything in between. But today we're going to focus on an important part of the technical answer namely: extensibility, through the WordPress hook system.

Today we are going to use an example of WordPress Plugin to cover the two key functions that confer extensibility status to a plugin namely: apply_filters() and do_action().

Extensions: extensions for plugins

It is therefore clear that when we speak of "extensions", we are referring to plugins that are made for others. Let's take an example: " Stripe for WooCommerce ».

This extension does nothing if you haven't already WooCommerce. If you install WooCommerce, then purchase and install " Stripe For WooCommerce As a separate plugin, and it will expand the functionality of WooCommerce so that you can start accepting payments via the Stripe payment gateway.

So you have a plugin that improves another plugin in a specific way. It's an extension. These are adverbs from the WordPress ecosystem.

How do the functions: apply_filters () and do_action () work?

The next question: how does WooCommerce come to see its extended functionality? After all, it's easy to imagine writing an eCommerce plugin that “ Only works with a few payment gateways ". Then, if you really want to Stripe you will have to completely modify WooCommerce, and probably end up creating your own tool called StripeCommerce, which either becomes a competitor of WooCommerce or simply lives on the site of one of your customers who could afford to pay personalized assistance.

It's a mess to contemplate, but luckily WooCommerce is doing something a lot better. It makes a use of two functions: apply_filters () and do_action (). These two functions allow you to create brackets on WordPress, and this is a fundamental part of the WordPress Hooks system in general.

apply_filters () and do_action () A rather simple difference:

  • apply_filters () allows you to connect filters to functions.
  • do_action () allows you to connect actions to functions.

Let's look at an example to see how they work.

Example of using WooPress hooks.

For our example, we'll be using a “Quote of the Day” plugin, plus an extension that modifies this plugin in a specific way. To follow and see the full code, download the plugins as a ZIP file https://wpshout.com/media/2016/10/plugins.zip.

The original plugin

This plugin uses the API exposed by an external quote library, and store the resulting quote as WordPress transient data which refreshes every 24 hours. Come back to this article anytime and you will see a random quote from this day on the topic of "life", which should be broad enough.

plugin extension

As we know, the problem with most quotes is that they are not said by "Carl Sagan". Our extension corrects this problem, using a number of tools:

  • A large header showing today's date and that the quote is by Carl Sagan,
  • Some specific word replacements to turn a quote into what Carl Sagan might have said
  • The authors of the original quotes are changed and the quotes are now correctly attributed to Carl Sagan.

Here's the plugin and extension, in action:

citation-in-action

The code

In order for this to happen, two steps are necessary:

The original plugin defines hooks - action hooks and filter hooks - allowing external code to modify or add its own code at key points. The plugin uses apply_filters () and do_action () to achieve this.

The extension defines hook functions on the action and filters - which modify the original plugin in a necessary way.

Key code in the original plugin

The most important part of the code for us is what we do after we get our data from the API. This data is available as an array with two elements: text: the text of the citation; and author: the person who said the quote. Our code will therefore look like this:

add_shortcode ('extensible_plugin_demo', 'bpc_output_extensible_plugin'); function bpc_output_extensible_plugin () {ob_start (); // Hook before display! do_action ('bpc_before_get_qod_text'); $ qod_data = bpc_get_qod_data (); if (is_array ($ qod_data)) {echo ' '; $ qod_text = $ qod_data ['text']; $ qod_author = $ qod_data ['author']; // Filter the content! $ qod_text = apply_filters ('bpc_qod_text', $ qod_text); $ qod_author = apply_filters ('bpc_qod_author', $ qod_author); echo $ qod_text; echo ' '; echo $ qod_author; echo ' '; } // Action hook after rest of output! do_action ('bpc_after_get_qod_text'); return ob_get_clean (); }

Key code in the extension

The plugin doesn't consist of anything other than actions and filters to modify the original plugin. Here is the code for the extension:

add_filter( 'bpc_qod_text', 'bpc_filter_qod_text' );
// Filter: remplacer des mots spécifique
function bpc_filter_qod_text( $text ) {
    $text = str_replace( 
        array( ' I ', ' me ', ' the ', ' is ', ' am ', ' are ' ),
        array( ' I, a descendent of savannah-dwelling hominids that somehow evolved an astounding capacity for self-reflection, ', ' the cooled-off stellar matter I call "me" ', ' the trillions of atoms that make up the ', ' seems, without the mind-boggling perspective of quantum physics, to be ', ' cannot, due to the Heisenberg Uncertainty Principle, be determined not to be ', ' appear to our best scientific instruments to be ' ),
        $text
    );
    return $text;
}

// Filter: barré le texte qui précède le nom de l'auteur et ajouter Carl Sagan à la suite
add_filter( 'bpc_qod_author', 'wpshout_filter_qod_author' );
function wpshout_filter_qod_author( $text ) {
    $text = '<strike>' . $text . '</strike> Carl Sagan';
    return $text;
}

// Action: Ajouter un titre
add_action( 'bpc_before_get_qod_text', 'bpc_set_up_quote' );
function wpshout_set_up_quote() {
    echo '<h4>Carl Sagan Quote of the Day for ' . date( 'F j, Y') . ':</h4>';
}

// Action: Ajouter une image
add_action( 'bpc_after_get_qod_text', 'bpc_add_carl_boom' );
function bpc_add_carl_boom() {

    echo '<div><img class="aligncenter" src="' . plugin_dir_url( __FILE__ ) . 'carl_sagan_mind_blown.gif"></div>';
}

As you can see, these are quite standard uses of " add_action () " and " add_filter () "And both functions are hooked on square brackets which we called" bpc_qod_text ".

The end result is that our plugin is now extensible: a second developer can watch modify the plugin and say "I want Carl Sagan to say », And do it while using the original plugin as a base a bit like parent and child themes on WordPress.

This is such a trick that makes a plugin like WooCommerce, very popular, allowing you to add new features.

That's it for this tutorial. I hope you understand better the different use cases of filters and WordPress actions.