Post
  • ecommerce
  • php
  • web development
  • Wordpress

Step-by-step guide to develop a WordPress plugin

When we want to extend functionality in WordPress project, we cannot do changes in core files because, WordPress updates frequently (currently at verion 5) and all changes will be overwritten back to default files of new version. Hence, the need for plugins for adding extra functionality. These are our experiences and process we employ at The Right Software to develop a WordPress plugin.

   
Step-by-step guide to develop a WordPress plugin

When we want to extend functionality in a WordPress project, we cannot make changes in core files because WordPress updates frequently (currently at version 6.4), and all changes will be overwritten back to the default files of the new version. Hence, there is a need for plugins to add extra functionality. There are steps to develop a plugin. WordPress also provides their own guide at  https://codex.wordpress.org/Writing_a_Plugin to create a plugin WordPress. However, that guide can be intimidating for new users. So, here we provide a step-by-step tutorial to develop a WordPress plugin. These are the experiences and processes we employ at The Right Software to develop a WordPress plugin.  We’ll go through some topics first and towards the end, develop a sample plugin (with code).

However, developing a WordPress plugin involves more than just coding; it requires a strategic approach to ensure scalability, security, and compatibility. In this comprehensive guide, we’ll walk you through the process of developing a WordPress plugin, incorporating additional functionalities, optimizing for search engines, and adhering to best practices. At The Right Software (TRS), our experienced developers have refined the plugin development process, and we’re excited to share our insights with you.

Topics explored

Begin the WordPress plugin development process by organizing your file structure. This step is crucial for maintaining a clean and efficient codebase:

  • Go to your WordPress installation’s wp-contentdirectory.
  • Open the plugins directory.
  • Create a new directory and name (e.g. test-plugin).
  • Open your new directory.
  • Create the main WordPress plugin PHP file (it’s also good to name e.g. test-plugin.php).
  • Create a readme.md file (discussed below) and write WordPress plugin descriptions and specifications.
file structure of wordpress plugin
Now, let’s start creating files for the plugin.

The WordPress plugin needs to block direct access to PHP files by checking ABSPATH variable is defined. For this, you need to add the following code at the top of all of the plugin PHP files. For this tutorial, that file is test-plugin.php. So make sure that if you have a library or multiple plugin files then the line below is added to all the files.

 defined( 'ABSPATH' ) or die( 'Nope, not accessing this' );
Plugin declarations are text comments that WordPress will use to define your entry in the plugin list. It must have a plugin name at least. You can also add plugin description, url, version, author, license, etc. All that will be in PHP comments quotes. The Plugin declaration block should be added to the main plugin PHP file.
<?php
/*
Plugin Name: WordPress Test Plugin
Plugin URI:  https://therightsw.com
Description: Test description
Version:     1.0.0
Author:      therightsw
Author URI:  http https://therightsw.com
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/
?>

Hooks are like tentacles that your WordPress plugin sinks into the WordPress core and extends or overrides the functionality. Three types of hooks are used in WordPress to override existing WordPress and add new functionality.

Filter hook

WordPress filter hooks can be added or removed and new ones can be created. To learn more about what a filter hook is, see Plugin API.

add_filter('the_content', 'custom_meta_to_content'); //gets our meta data and dispayed it before the content

Action hook

WordPress action hooks can be added or removed and also new ones can be created. To learn more about what an action hook is, see Plugin API..

add_action('admin_enqueue_scripts', 'enqueue_admin_scripts_and_styles'); //admin scripts and styles

Shortcode

Mostly defined and used for adding extra functionality.

add_shortcode('wp_custom_text', 'func_wp_custom_text'); //will be used to add custom text by adding this shortcode where you want.

Activation and Deactivation Hooks

Use register_activation_hook and register_deactivation_hook to execute functions upon plugin activation or deactivation.

If you want to learn about WordPress hooks and WooCommerce hooks, you can visit below article.

Related: WordPress Hooks: Actions & Filters

Security is paramount in WordPress development. Follow these guidelines to ensure your plugin meets the highest security standards:

Generic function by using unique function and class names

All plugins must have unique function names, definitions, and class names. This prevents your plugin from conflicting with other plugins or themes. Also good for having your plugin approved by WordPress.

For example, if your plugin is called “Easy Custom Post Types“, then you might prefix your functions with ecpt_{your function name here}. Similarly, a definition of LICENSE would be better done as ECPT_LICENSE. You can use namespaces instead, however, make sure that those also are unique. A namespace or class  MyPlugin is NOT all that unique.

This extends to anything in a definition. For example, if you were to use this, it would be a bad idea:

define( 'PLUGIN_PATH', plugins_url( __FILE__ ) );

That definition is global, so PLUGIN_PATH could conflict with several other things.

Don’t try to use two-letter slugs anymore. As of 2016, all the good ones are taken. Instead, consider easy_cpts_ (from the first example).

Similarly, don’t use __ (double underscores), wp_, or _ (single underscore) as a prefix. Those are reserved for WordPress itself. You can use them inside your classes, but not as a stand-alone function.

Use more unique functions and class names for your plugin.

Use Nonces and Check Permissions

Implement nonces in POST calls to prevent unauthorized access.

When you include POST/GET/REQUEST calls in your plugin, it’s important to sanitize, validate, and escape them. The goal here is to prevent a user from accidentally sending trash data through the system, as well as protecting them from potential security issues.

Sanitize:

In all instances where generated content is inserted into the database, into a file, or otherwise processed by WordPress, the data MUST be properly sanitized for security. By sanitizing your POST data when used to make action calls or URL redirects, you will lessen the possibility of XSS vulnerabilities. You should never have raw data inserted into the database, even by an update function, and even with a prepare() call.

If you had a text input field like

<input name="your-name" type="text" />

You could sanitize it using the sanitize_text_field() function.

$name = sanitize_text_field( $_POST['your-name'] );
update_post_meta( $post->ID, 'your-name', $name );

Other functions used for sanitizing the data are.

  • sanitize_email()
  • sanitize_file_name()
  • sanitize_html_class()
  • sanitize_key()
  • sanitize_meta()
  • sanitize_mime_type()
  • sanitize_option()
  • sanitize_sql_orderby()
  • sanitize_text_field()
  • sanitize_textarea_field()
  • sanitize_title()
  • sanitize_title_for_query()
  • sanitize_title_with_dashes()
  • sanitize_user()

 

Validate:

In addition to sanitization, you should validate all your calls. If a $_POST call should only be a number, ensure it’s an int() before you pass it through anything. Even if you’re sanitizing or using WordPress functions to ensure things are safe, we ask you to please validate for sanity’s sake. Any time you are adding data to the database, it should be the right data.

For example, if you want zip code in integers then intval() function will be used to validate the input value.

$zipcode = intval( $_POST['zipcode'] );

Escape:

When you’re outputting data, make sure to escape it properly, so it can’t hijack admin screens. There are many esc_*() functions you can use to make sure you don’t show people the wrong data.

In all cases, using stripslashes or strip_tags is not enough. You need to use the most appropriate method associated with the type of content you’re processing. Check that a URL is a URL and don’t just be lazy and use sanitize_text, please. The ultimate goal is that you should ensure that invalid and unsafe data is NEVER processed or displayed. Clean everything, check everything, escape everything, and never trust the users to always have input sane data.

Some commonly used helper functions

esc_html() used HTML element to enclose a section of data we’re outputting. <h2><?php echo esc_html( $title ); ?></h2>

esc_url() used for all URLs of HTML element. <img src="<?php echo esc_url( $great_user_picture_url ); ?>" />

esc_js() is intended for inline Javascript. <a href="#" onclick="<?php echo esc_js( $custom_js ); ?>">Click me</a>

esc_attr() can be used on the data into an HTML element’s attribute. <div id="<?php echo esc_attr( $element_id ); ?>"></div>

esc_textarea() encodes in textarea element. <textarea><?php echo esc_textarea( $text ); ?></textarea>

Now, let’s develop your first WordPress plugin. As an example, I am going to create a sample plugin that will be used to add custom text (it could be a simple paragraph or heading, etc.) anywhere on the website. You can download this small sample plugin using the link at the bottom of the article.

1) Create a plugin directory in /wp-content/plugins and name it WordPress-Custom-Text-Shortcode.

2) Create trs-custom-text.php file and add plugin declaration:

<?php
/*
Plugin Name: WordPress Custom Text Shortcode
Plugin URI:  https://therightsw.com
Description: You can add your desired text anywhere in website by using WordPress Custom Text Shortcode.
Version:     1.0.0
Author:      therightsw
Author URI:  http https://therightsw.com
License:     GPL2
License URI: https://www.gnu.org/licenses/gpl-2.0.html
*/

3) Activation/Deactivation:

function wp_custom_text_activation() {
}
register_activation_hook(__FILE__, 'wp_custom_text_activation');
function wp_custom_text_deactivation() {
}
register_deactivation_hook(__FILE__, 'wp_custom_text_deactivation');

4) Create custom menu hook to diplsay plugin menu in wp-admin:

// create custom plugin settings menu
add_action('admin_menu', 'wp_custom_text_create_menu');

function wp_custom_text_create_menu() {

	//create new top-level menu
	add_menu_page('Custom Text Shortcode Plugin Settings', 'Custom Text Shortcode', 'administrator', __FILE__, 'wp_custom_text_settings_page' );

	//call register settings function
	add_action( 'admin_init', 'register_wp_custom_text_settings' );
}

5) Register plugin setting:

function register_wp_custom_text_settings() {
	//register our settings
	register_setting( 'trs-custom-text-settings-group', 'wp_custom_text' );
}

6) Setting display page code:

function wp_custom_text_settings_page() {
?>
<div class="wrap">

<h1>Your Custom Text></h1>

<form method="post" action="options.php">
    
    
   <table class="form-table">
      <tr valign="top">
        <th scope="row" </td>
        </tr>
    </table>
    

</form>

</div>

7) Create shortcode used to display custom text:

add_shortcode("wp_custom_text_shortcode", "wp_custom_text_shortcode_function");

function wp_custom_text_shortcode_function() {
return get_option( 'wp_custom_text' );
}

If you plan to submit  the plugin you developed to the WordPress.org plugins directory, it’s essential to adhere to a specific file structure for approval:

  • Readme.md File: Contains essential information about your plugin.
  • Assets folder: Houses plugin screenshots, CSS, and JS files.
  • Trunk folder: Stores the plugin’s PHP files.

Remember, the .git folder is for internal use and can be discarded. Since WordPress.org utilizes SVN version control, not Git, keep your structure compliant.

WordPress-plugin-structure-approved-4

Regular updates

Stay proactive with updates to address security issues, improve functionality, and maintain compatibility with the latest WordPress versions.

User-Friendly interfaces

Design an intuitive and user-friendly interface for your plugin settings. Clear navigation and instructions contribute to a positive user experience.

Comprehensive documentation

Provide detailed documentation for your plugin, including installation guides, FAQs, and troubleshooting tips. This helps users understand and utilize your plugin effectively.

Testing across environments

Test your plugin in various environments to ensure compatibility with different server configurations, PHP versions, and WordPress setups.

Download above sample plugin from given link. https://github.com/TheRightSoftware/WordPress-Custom-Text-Shortcode

If you follow this detailed tutorial, you can learn to Develop a WordPress plugin. If you get stuck, fill out the form below, and we’ll be right with you. We also provide plugin development services for WordPress and all other CMS and eCommerce software.

You can also check and download our free plugins.  These plugins can be seamlessly integrated into your WordPress site, offering a secure and free solution.

Related: 8 Highly Recommended WordPress Plugins 

We hope this article has provided you with valuable insights and knowledge to enhance your plugin development projects. You can contact The Right Software to hire a Plugin development expert to perform these steps for you!

Frequently Asked Questions (FAQs)

What is the importance of developing a WordPress plugin?
Developing a WordPress plugin is crucial for extending the functionality of a WordPress project without making changes to core files, which may be overwritten during updates.
The article outlines several steps, including organizing the file structure, creating plugin declarations, using WordPress hooks, and securing the plugin.
The recommended file structure involves creating a new directory within the wp-content/plugins directory, adding the main PHP file, and including a readme.md file with plugin description and specifications.

For approval on WordPress.org, we suggest adhering to a specific file structure that includes a readme file, an assets folder for screenshots and files, and a trunk folder for PHP files.

We recommend regular updates, user-friendly interfaces, comprehensive documentation, and testing across different environments as best practices for WordPress plugin development.

We emphasize the use of unique functions and class names, implementing nonces for POST calls, and sanitizing, escaping, and validating POST data to enhance security.