How to Create a WordPress Plugin for Your Web App

WordPress powers over 40% of all websites on the internet, making it a critical platform to integrate with for many web applications. One of the best ways to seamlessly connect your app with WordPress is by creating a custom plugin. As a full-stack developer, you can build a WordPress plugin to automatically insert your app‘s code and communicate with its API.

In this in-depth guide, we‘ll walk through the complete process of developing a WordPress plugin for a web application. Whether you want to add your SaaS product, marketing tool, or analytics solution to WordPress sites, these principles and techniques will help you create a solid plugin.

What is a WordPress Plugin?

A WordPress plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites.

Plugins allow you to greatly customize the behavior and features of your website without having to modify the core WordPress code. There are thousands of free and paid plugins available that handle everything from contact forms to backups to ecommerce.

For web apps, a dedicated WordPress plugin provides a way to integrate with websites without requiring the site owner to manually edit their theme templates. The plugin can add the necessary code snippets and provide an interface for configuring API keys and settings.

Some examples of web apps that offer WordPress plugins for easy integration include:

  • Google Analytics
  • Intercom
  • Disqus
  • Zapier
  • Yoast SEO
  • Mailchimp
  • WP Forms
  • WooCommerce

Creating an official plugin for your web app makes it simple for WordPress users to install and set up, which can help drive adoption.

Requirements and Tools

To follow along with this tutorial and develop a WordPress plugin, you will need:

  • A local WordPress development environment (e.g. MAMP, WAMP, Local, etc.)
  • Familiarity with PHP and object-oriented programming concepts
  • Basic knowledge of JavaScript and jQuery
  • A code editor (e.g. VS Code, Sublime Text, PhpStorm, etc.)
  • A web app or service to integrate with (we‘ll use a generic example)
  • The app‘s API documentation and any necessary credentials

I also recommend referring to the official WordPress Plugin Handbook for best practices and guidelines:
https://developer.wordpress.org/plugins/

With the preliminary requirements out of the way, let‘s dive into actually building our plugin!

Setting Up the Plugin Architecture

WordPress plugins have a relatively simple structure. At the bare minimum, a plugin is a single PHP file with a plugin header comment.

Let‘s create a new folder for our plugin in /wp-content/plugins/ and name it after our app – in this example we‘ll call it my-app-plugin.

Inside that folder, create a new file called my-app-plugin.php and add the following code to get started:

<?php
/*
Plugin Name: My App Plugin
Plugin URI: https://myapp.com/ 
Description: Official WordPress plugin for integrating with My App.
Version: 1.0
Author: My App Team
Author URI: https://myapp.com/
*/

if ( ! defined( ‘ABSPATH‘ ) ) {
    exit; // Exit if accessed directly
}

class MyApp_Plugin {

    public function __construct() {
        // constructor
    }

}

$myAppPlugin = new MyApp_Plugin();

This is the basic skeleton of a WordPress plugin.

At the top we have a PHP docblock comment with metadata about the plugin. This is required for WordPress to recognize the file as a plugin.

Below that we have a check to prevent the file from being accessed directly for security purposes. And finally we have a class definition for our plugin with a constructor method.

We‘ll flesh out this class with properties and methods to handle the integration with our app. But first let‘s create a couple subfolders to organize the plugin‘s files:

  • /assets/css/ – for stylesheets
  • /assets/js/ – for scripts
  • /includes/ – for additional PHP class files

Creating the Admin Settings Page

Most WordPress plugins utilize the provided hooks system to "hook into" the core platform. This allows you to run your plugin code when certain events occur.

To create a settings page for our plugin in the WordPress admin area, we will use the admin_menu hook. This allows us to add a new menu item and subpage.

Add the following code in the constructor to create an admin page and options:

public function __construct() {
    add_action( ‘admin_menu‘, array( $this, ‘create_admin_menu‘ ) );
    add_action( ‘admin_init‘, array( $this, ‘register_settings‘ ) );
}

public function create_admin_menu() {
    add_options_page(
        ‘My App Settings‘,
        ‘My App‘,
        ‘manage_options‘,
        ‘my-app-plugin‘,
        array( $this, ‘admin_page_html‘ )
    );
}

public function admin_page_html() {
    // check user capabilities
    if ( ! current_user_can( ‘manage_options‘ ) ) {
        return;
    }

    ?>
    <div class="wrap">

        <form action="options.php" method="post">
            <?php
            settings_fields( ‘my-app-plugin‘ );
            do_settings_sections( ‘my-app-plugin‘ );
            submit_button( ‘Save Settings‘ );
            ?>
        </form>
    </div>
    <?php
}

public function register_settings() {
    register_setting(
        ‘my-app-plugin‘, // option group
        ‘my-app-plugin‘, // option name
        array( $this, ‘sanitize‘ ) // sanitization callback
    );

    add_settings_section(
        ‘my_app_settings‘, // id
        ‘My App Settings‘, // title
        array( $this, ‘section_info‘ ), // callback
        ‘my-app-plugin‘ // page
    );

    add_settings_field(
        ‘api_key‘, // id
        ‘API Key‘, // title
        array( $this, ‘api_key_callback‘ ), // callback
        ‘my-app-plugin‘, // page
        ‘my_app_settings‘ // section           
    );

    add_settings_field(
        ‘enable_tracking‘,
        ‘Enable Tracking‘, 
        array( $this, ‘tracking_callback‘ ),
        ‘my-app-plugin‘,
        ‘my_app_settings‘     
    );

}

public function section_info() {
    echo ‘<p>Enter your My App API key and configure settings below:</p>‘;
}

public function api_key_callback() {
    $apiKey = isset( $this->options[‘api_key‘] ) ? $this->options[‘api_key‘] : ‘‘;
    echo ‘<input type="password" name="my-app-plugin[api_key]" value="‘ . esc_attr( $apiKey ) . ‘" />‘;
}

public function tracking_callback() {
    $enableTracking = isset( $this->options[‘enable_tracking‘] ) ? $this->options[‘enable_tracking‘] : 0;
    echo ‘<input type="checkbox" name="my-app-plugin[enable_tracking]" value="1"‘ . checked( 1, $enableTracking, false ) . ‘/>‘;
}

public function sanitize( $input ) {
    $sanitary_values = array();
    if ( isset( $input[‘api_key‘] ) ) {
        $sanitary_values[‘api_key‘] = sanitize_text_field( $input[‘api_key‘] );
    }

    if ( isset( $input[‘enable_tracking‘] ) ) {
        $sanitary_values[‘enable_tracking‘] = intval($input[‘enable_tracking‘]);
    }

    return $sanitary_values;
}

This code registers a new "My App" options page under the Settings menu in WordPress admin. It defines the form fields for API key and enable tracking toggle.

The register_settings() function registers the plugin settings with WordPress so they can be securely saved to the database. The sanitize() method is a callback to validate and sanitize the options before storing.

Inserting the App Code

Now that the plugin foundation and settings are in place, it‘s time to actually insert our app‘s code snippet into the front-end of the WordPress site.

Our hypothetical web app requires its JavaScript snippet to be loaded on every page, like Google Analytics for example. To conditionally insert the snippet based on the enable tracking setting, we can hook into WordPress‘ wp_footer action.

Add this code to the constructor:

add_action( ‘wp_footer‘, array( $this, ‘insert_tracking_code‘ ) );

Then define the insert_tracking_code() callback function:

public function insert_tracking_code() {

    $options = get_option(‘my-app-plugin‘);

    // Only insert code if enabled in settings
    if( isset($options[‘enable_tracking‘]) && $options[‘enable_tracking‘] == 1 ) {

        $apiKey = $options[‘api_key‘];

        echo "
        <script src=‘https://myapp.com/script.js‘></script>
        <script>
            myApp.init(‘$apiKey‘);
        </script>";

    }

}

This will output the app‘s script tag and initialize it with the API key from the plugin settings, but only if the tracking option is enabled.

You can use a similar approach to insert header code or only on certain pages by using other hooks like wp_head and conditional tags like is_single(), is_page(), etc.

Calling the App API

Depending on your web app, the WordPress plugin may need to fetch or send data via an API. You can use WordPress‘ built-in wp_remote_get() and wp_remote_post() functions to make HTTP requests.

Here is an example of making a GET request to retrieve a user‘s info from our app‘s API:

$options = get_option(‘my-app-plugin‘);

$apiKey = $options[‘api_key‘];
$userId = get_current_user_id();

$response = wp_remote_get( ‘https://api.myapp.com/v1/users/‘. $userId, array(
    ‘headers‘ => array(
        ‘Authorization‘ => ‘Bearer ‘ . $apiKey,
    )
) );

if ( is_array( $response ) && ! is_wp_error( $response ) ) {
    $body = json_decode( $response[‘body‘] );
    $userEmail = $body->email;
    // do something with $userEmail
}

This sends an authenticated request to our app‘s /users endpoint to retrieve the WordPress user‘s email address, which could then be used to auto-identify them.

You can use a similar approach to send tracking events, update account info, or pull in data to display from your app. Just be mindful to handle any errors and ensure the API key or other sensitive info is never exposed client-side.

The specific API implementation will depend on what your service offers and what you want to sync with WordPress. But the general pattern of saving credentials, making server-side API calls, and utilizing the responses holds true.

Finishing Touches and Best Practices

With the core functionality of the settings page and inserting code in place, there are few more considerations and best practices to follow when developing a WordPress plugin:

Internationalization

It‘s always a good idea to make your plugin translatable. You can use WordPress‘ i18n functions like __() and _e() to wrap translatable strings.

Here‘s an example of translating our plugin‘s admin page title:

Security

Sanitizing and validating any data coming from the user is critical in WordPress plugins. We already sanitized the form inputs in our sanitize() function, but you should also use functions like esc_html(), esc_attr(), and esc_url() when outputting any user-provided data.

Additionally, use nonces to verify the origin of admin requests and check user capabilities to restrict access to admin functions.

Code Organization

As your plugin grows in complexity, it‘s a good idea to split the functionality into separate classes or files. A common pattern is to create a separate class for admin functions and one for public functions. You can use the includes/ folder we created earlier to store these files.

Documenting and Commenting

Whether you plan to release your plugin publicly or just use it internally, it‘s important to document how it works. At a minimum, include a README file with an overview, installation steps, FAQ, and a changelog.

Use PHPDoc-style comments to document your classes and functions. This will make it easier for other developers (including your future self) to understand how your plugin works.

Testing and Debugging

Before releasing your plugin, be sure to thoroughly test it on different WordPress versions and with different themes and plugins. Use WordPress‘ debugging constants to log errors and notices.

Some helpful tools for debugging include:

  • Query Monitor plugin
  • Debug Bar plugin
  • WordPress‘ built-in debug log
  • Browser developer tools

Deployment and Updates

If you plan to release your plugin publicly on WordPress.org or GitHub, you‘ll want to follow the WordPress plugin submission guidelines and set up a system for managing updates.

Use semantic versioning for releases and include a detailed changelog. You can use GitHub releases or a plugin update server to push out new versions of your plugin to users.

Wrapping Up

Creating a WordPress plugin to integrate your web app provides a seamless way for users to add your service to their websites. By leveraging WordPress‘ hooks and functions, you can build a custom admin interface, insert your app‘s code snippet, sync data via API, and more.

The key things to remember are:

  • Keep your plugin code organized and well-documented
  • Use WordPress‘ built-in functions for security and internationalization
  • Hook into the appropriate actions and filters to modify WordPress‘ behavior
  • Sanitize and validate any user input
  • Make API calls server-side using WordPress‘ HTTP API functions
  • Test thoroughly and provide clear documentation

I hope this guide has given you a solid foundation for creating a WordPress plugin for your web app. With some PHP knowledge and an understanding of the WordPress plugin API, you can build a powerful integration to grow adoption of your service.

Here are some helpful resources for further reading:

Do you have any experience building WordPress plugins? What tips or best practices would you add? Let me know in the comments!

Similar Posts