The Ultimate Guide to WordPress Plugin Development: Building Your First Custom Plugin from Scratch

3-minute read
2026-03-13
2026-06-04
2,841
I earn commissions when you shop through the links below, at no additional cost to you.

Why choose WordPress plugin development?

The reason WordPress has become the most popular content management system (CMS) in the world is largely due to its powerful scalability, which is attributed to its plugin architecture. By developing custom plugins, you can add any feature you can imagine to your website without having to modify the core code of WordPress itself. This means that these features can exist independently of the theme used, and they will remain intact even if you switch to a different theme. More importantly, a well-designed plugin can address specific needs of users, and in some cases, it can even become a standalone product or service.

Mastering plugin development means that you are transitioning from a WordPress user to a creator. Whether it’s to meet the customized needs of your own projects or to generate income by developing commercial plugins, understanding the core principles and best practices of plugin development is an essential first step. This guide will guide you from the most basic structures, step by step, to building a fully functional and standard-compliant plugin.

Building your first plugin structure

A standard WordPress plugin is a folder that contains one or more PHP files, and its root directory must include a main file. This main file must contain specific plugin header information so that WordPress can recognize and manage it.

Recommended Reading Master WordPress Plugin Development: Build Efficient Custom Functional Modules from Scratch

Create the main file of the plug-in

The first thing you need to do is create the main file for the plugin. This file is usually named after the plugin itself, for example… my-first-plugin.phpAt the top of this file, you must add a standard plugin header comment.

UltaHost WordPress Hosting
30-day refund guarantee, unlimited bandwidth and database usage, free DDoS protection; purchase for 3 years and get a discount of 50%.
<?php
/**
 * Plugin Name:       我的第一个自定义插件
 * Plugin URI:        https://yourwebsite.com/my-first-plugin
 * Description:       这是一个用于学习的 WordPress 自定义插件示例。
 * Version:           1.0.0
 * Author:            你的名字
 * Author URI:        https://yourwebsite.com
 * License:           GPL v2 or later
 * Text Domain:       my-first-plugin
 * Domain Path:       /languages
 */

This comment is the “identity document” of the plugin. Plugin Name(The plugin name) is the only required field; the other fields are used to provide additional information. The “Plugins” page in the WordPress administration dashboard will read this information and display it. After creating this file, you need to place it in the WordPress installation directory. /wp-content/plugins/ It’s inside the folder. You can create a sub-folder named “my-first-plugin” and then place the main file there. Now, log in to the WordPress administration panel, and you should be able to see and activate the plugin in the plugin list. Although it doesn’t have any functionality yet, you’ve taken the first successful step.

Organize your plugin files.

As more features are added, it becomes difficult to maintain all the code in a single main file. A good file organization structure is essential. A typical plugin may include the following directories:
* /includes/This folder contains the files that define the core functions and classes of the system.
* /admin/These files are used for the backend administration interface.
* /public/These files contain the front-end functionality that is intended for website visitors.
* /assets/This folder is used to store static resources such as JavaScript files, CSS files, and images.
* /languages/Used to store internationalization translation files (.po/.mo).

This modular structure not only makes the code clearer but also facilitates team collaboration and future feature expansions. In the main file… my-first-plugin.php In this context, you would usually use… require_once To introduce the function files located in these directories.

Understanding the core development concepts of WordPress: Hooks and Filters

The core of WordPress plugin development is the “Hook” mechanism. This mechanism allows your code to be integrated into WordPress’s core execution process at specific points in time, enabling you to modify or add new functionality. There are two types of hooks: Actions and Filters.

Recommended Reading Mastering WordPress Plugin Development from Scratch: A Guide to Advanced Features and Best Practices

Use action hooks to add functionality.

Action hooks allow you to execute your custom functions at specific moments during the WordPress workflow. For example, you might want to perform an action when an article is published, or add a menu to the sidebar of the admin panel.

Here is a simple example that uses… wp_footer This action hook is used to display a message in the public area at the bottom of the website page. You need to add the following code to your plugin’s main file.

function myplugin_add_footer_text() {
    echo '<p style="text-align:center;">Thank you for using my first plugin!</p>';
}
add_action( 'wp_footer', 'myplugin_add_footer_text' );

Here,myplugin_add_footer_text It is a function that we have defined.add_action() The function “binds” this function to another entity or context. wp_footer This action is hooked onto a specific hook. Whenever WordPress processes the footer section of the page, our function will be automatically invoked.

hosting.com Shared Hosting
High performance with AMD EPYC CPUs, NVMe SSD storage and LiteSpeed, 24/7, 24x7 expert in-house support, advanced security measures including SSL, brute force, malware and DDoS protection, savings of up to 73%

Use the filter hook to modify the content.

Unlike action hooks, filter hooks are used to modify data. Your function will receive an input value, and after processing it, you must return a value. For example, you could modify the title of an article or change the way the content is displayed.

The following example demonstrates how to use… the_content A filter that automatically adds a custom piece of text at the end of all articles and page contents.

function myplugin_append_to_content( $content ) {
    $custom_text = '<div class="myplugin-note"><p><em>This article is displayed with enhanced functionality thanks to my custom plugin.</em></p></div>';
    // 仅在主循环的单篇文章页面添加
    if ( is_single() &amp;&amp; in_the_loop() &amp;&amp; is_main_query() ) {
        return $content . $custom_text;
    }
    return $content;
}
add_filter( 'the_content', 'myplugin_append_to_content' );

function myplugin_append_to_content Receive the original $contentWe use conditional logic to ensure that text is only added where it is necessary, and then we return the modified content.add_filter() The function has completed the registration process.

Recommended Reading From Beginner to Expert: Developing WordPress Plugins: Building Custom Functions and Efficient Extensions

Create a management page for the plugin.

Most plugins require a configuration page that allows users to set options. WordPress provides a rich API for creating beautiful, standard management interfaces.

Add a top-level management menu.

You can add a new top-level menu item for your plugin to the left sidebar in the WordPress admin dashboard. Here’s how to do it: add_menu_page() This is implemented by functions. We usually… admin_menu This function is called within this action hook.

InterServer Shared Hosting
Shared hosting $2.50 USD per month , first month $0.1 USD promo code tryinterserver, 461 cloud apps scripts, one click install.
function myplugin_add_admin_menu() {
    add_menu_page(
        '我的插件设置', // 页面标签
        '我的插件',     // 菜单标题
        'manage_options', // 所需权限
        'myplugin-settings', // 菜单 Slug
        'myplugin_settings_page_html', // 显示页面内容的回调函数
        'dashicons-admin-generic', // 图标(可选)
        80 // 菜单位置(可选)
    );
}
add_action( 'admin_menu', 'myplugin_add_admin_menu' );

\n Construct the content of the setup page

Now we need to define the callback functions mentioned above. myplugin_settings_page_htmlThis is used to render the HTML content of the settings page. A simple version is as follows:

function myplugin_settings_page_html() {
    // 检查用户权限
    if ( ! current_user_can( 'manage_options' ) ) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1></h1>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 输出设置字段和非ce字段
            settings_fields( 'myplugin_options' );
            do_settings_sections( 'myplugin-settings' );
            submit_button( '保存设置' );
            ?>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

This function creates a form that conforms to the WordPress backend style. To fully process the settings, you will also need to use… register_setting(), add_settings_section() and add_settings_field() Functions such as these are used to define specific settings items, which together form the complete “Settings API” workflow. This represents the recommended approach for securely storing and retrieving plugin options.

Implement a practical plugin feature: Article view count statistics.

Let’s combine the above concepts to create a practical feature: one that counts and displays the number of views for each article.

Create database fields and store data.

First of all, we need to create a place to store the number of views when an article is published. Usually, we use the post meta (article metadata) functionality in WordPress. We can utilize this feature to... add_post_meta A function could be used for this purpose, but a more elegant approach would be to check and update this value whenever the article is viewed.

function myplugin_track_post_views( $post_id ) {
    if ( ! is_single() ) {
        return;
    }
    if ( empty( $post_id ) ) {
        global $post;
        $post_id = $post->ID;
    }
    // 获取当前浏览次数
    $count = get_post_meta( $post_id, 'myplugin_post_views', true );
    // 如果为空,初始化为0
    $count = $count ? absint( $count ) : 0;
    $count++;
    // 更新数据库
    update_post_meta( $post_id, 'myplugin_post_views', $count );
}
// 在模板重定向时触发,确保只对真实访客计数
add_action( 'template_redirect', 'myplugin_track_post_views' );

Display the number of views on the front end.

After the data is stored, we need a function to retrieve and display it. We can create a Shortcode that makes it easy for users to insert it into the article content or sidebar widgets.

function myplugin_display_post_views_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' =&gt; get_the_ID(),
    ), $atts, 'myplugin_views' );

$post_id = absint( $atts['id'] );
    $views = get_post_meta( $post_id, 'myplugin_post_views', true );
    $views = $views ? $views : 0;

return '<span class="myplugin-view-count">Number of views: ' . esc_html($views) . '</span>'php
add_shortcode('myplugin_views', 'myplugin_display_post_views_shortcode');

Now, users simply need to enter a code in the article editor. [myplugin_views]Alternatively, you can add a “shortcut” widget using a small tool and enter that shortcut to display the number of views for the article on the page. This complete example covers the entire process, including data storage (hooks), data retrieval, and front-end display (the shortcut).

summarize

By following this guide, you have completed the entire process of building a custom WordPress plugin from scratch. We started by understanding the basic structure of a plugin and created the main file that contains the standard header information. Next, we delved into the core concepts of WordPress plugin development: hooks (actions and filters), and learned how to use them to add or modify functionality. We then created a professional administration page for the plugin, which is crucial for interacting with users. Finally, we put the theory into practice with a real-world example of “article view count statistics,” implementing a complete functional chain that handles data storage and display on the front end.

Remember: Excellent plugin development is not just about making the features work; it’s also about ensuring the code is secure, maintainable, performant, and complies with WordPress’s coding standards. By practicing regularly and exploring the WordPress API, you will be able to create plugins that are powerful and well-received by users.

FAQ Frequently Asked Questions

What prerequisites are required to develop plugins?

You need to have a solid foundation in PHP programming, as WordPress and its plugins are primarily written in PHP. It is also essential to have a basic understanding of HTML, CSS, and JavaScript, as these technologies are used to create user interfaces and interactive features. Familiarity with the basic concepts of MySQL databases will be helpful in understanding how WordPress stores data.

How to debug my WordPress plugin?

First of all, make sure that in your… wp-config.php Enable WordPress debugging mode in the file. WP_DEBUG The constant is set to trueThis will display PHP errors and warnings on the screen. Secondly, use… error_log() The function writes debugging information to the server’s error log, which is a very reliable method for debugging. For complex variables, this approach can be used in conjunction with other techniques. print_r() Or var_dump() and error_log()In addition, use the browser developer tools (F12) to debug issues with front-end JavaScript and CSS.

How can my plugin be compatible with different versions of WordPress?

During development, it is important to regularly refer to the official WordPress development documentation to stay informed about changes in functions and hooks across different versions. function_exists() Or version_compare() Use conditional statements to check whether a certain function or feature is available, and provide a backward-compatible alternative solution accordingly. Clearly state the range of WordPress versions for which compatibility is guaranteed in the plugin description. It is best practice to continuously test the plugin in multiple versions of WordPress to ensure compatibility.

What should be considered when developing commercial plugins?

When developing commercial plugins, security, code quality, and user experience must be of the highest priority. You need to implement a reliable and secure authorization system (such as using license keys). Providing clear and timely user documentation and technical support is crucial. Make sure to comply with the official WordPress plugin development guidelines and the GPL license agreement. Consider using professional platforms like Freemius or Easy Digital Downloads to handle sales, update notifications, and support requests.