An Introduction to WordPress Plugin Development: Building Your First Functional Extension from Scratch

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

Preparatory Work: Understanding the Basics of WordPress Plugins

Before starting to write code, it is crucial to establish a solid theoretical foundation. A WordPress plugin is essentially a collection of one or more PHP files that function through the mechanisms provided by WordPress.Hook(钩子)The system allows for the extension or modification of WordPress’s core functionality. Plugins can range from being as simple as adding a single piece of code to being as complex as creating a complete administrative backend application. All plugins are stored in a specific location within the WordPress framework./wp-content/plugins/Under the directory, each plug-in has its own independent folder.

The development environment is your workbench. You need a local server environment, such as XAMPP, MAMP, or Local by Flywheel, and you should also install WordPress on it. It is highly recommended to…wp-config.phpThe file is open in the programWP_DEBUGThis pattern will help you quickly locate errors during the development process. In addition, a handy code editor (such as VS Code or PhpStorm) and a modern browser with developer tools are also essential.

Creating the first plugin: Basic structure and activation

Let’s start by creating the simplest plugin possible, which will add a line of copyright information at the bottom of all pages on the website. This process will help you understand the basic components of a plugin.

Recommended Reading A Beginner's Guide to WordPress Plugin Development: Building Your First Functional Extension from Scratch

Firstly, in/wp-content/plugins/Create a new folder in the directory and name it…my-first-pluginWithin this folder, create the main plugin file, which usually has the same name as the folder itself.my-first-plugin.phpEvery plugin must have a standard plugin header comment; this is the only way for WordPress to identify plugin information.

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://example.com/my-first-plugin
 * Description:       这是一个用于学习WordPress插件开发的入门插件,将在页面底部添加版权信息。
 * Version:           1.0.0
 * Author:            你的名字
 * License:           GPL v2 or later
 * Text Domain:       my-first-plugin
 */

After saving the file, log in to your WordPress administration panel and navigate to the “Plugins” page. You will see a plugin named “My First Plugin” in the list. Click “Activate” to officially activate it; although it won’t perform any functions yet, it will be ready for use in the future.

Implement the core functionality: Use hooks to add content.

The strength of WordPress lies in its...Hook(钩子)The system is divided into…Action(动作)andFilter(过滤器)There are two types of hooks available. Action hooks allow you to insert your own code at specific points in time, such as when the page has finished loading or when an article is published, in order to perform certain functions. Filter hooks, on the other hand, enable you to modify the data that is being passed through the process (for example, the content or title of an article).

In order to add text to the footer, we need to usewp_footerThis action hook: We add the following code to the main plugin file.

// 这是一个安全措施,防止直接访问PHP文件
if ( ! defined( 'ABSPATH' ) ) {
    exit; // 如果ABSPATH未定义,则退出
}

/**
 * 在网站页脚输出自定义HTML内容
 */
function myfp_add_footer_text() {
    echo '<div style="text-align: center; padding: 20px; border-top: 1px solid #eee; margin-top: 40px;">'echo '<p>© ' . date('Y') . ' My Website. All rights reserved. This content is created by<strong>My first plugin</strong>Generate.</p>'echo '</div>';
}
// 将我们的函数挂载到 `wp_footer` 动作钩子上
add_action( 'wp_footer', 'myfp_add_footer_text' );

In this code snippet, we first define the function.myfp_add_footer_text()Its function is to generate a piece of HTML code. Then, we use it…add_action()The function “mounts” this custom function to…wp_footerOn this hook. This means that whenever WordPress executes the code that comes after this hook…wp_footerWhen it comes to location (usually located within the topic)...footer.phpWhenever the file is loaded, our function will be automatically executed, and the copyright information we defined will be displayed at the bottom of the page.

Recommended Reading Starting from scratch: A complete guide to WordPress plugin development and sharing of best practices

Advanced Features: Creating Management Pages and Shortcodes

A fully functional plugin usually requires interaction with the administrator. Next, we will add a simple configuration page for the plugin and create a short code (a piece of code that can be used to activate or customize the plugin’s functionality).

Add a settings page to the management menu.

We will useadd_menu_page()The function adds a new item to the left-side menu in the WordPress backend. Modify the main plugin file and add the following code:

/**
 * 注册插件管理菜单
 */
function myfp_add_admin_menu() {
    add_menu_page(
        '我的第一个插件设置', // 页面标题
        '我的插件',           // 菜单标题
        'manage_options',     // 所需权限
        'myfp-settings',      // 菜单slug
        'myfp_settings_page', // 显示页面内容的回调函数
        'dashicons-admin-plugins', // 图标(使用Dashicon)
        30                    // 菜单位置
    );
}
add_action( 'admin_menu', 'myfp_add_admin_menu' );

/**
 * 设置页面的HTML内容
 */
function myfp_settings_page() {
    // 检查用户权限
    if ( !current_user_can( 'manage_options' ) ) {
        return;
    }
    ?&gt;
    <div class="wrap">
        <h1></h1>
        <p>Welcome to the settings page for “My First Plugin.” This is a simple example of a management interface.</p>
        <form action="/en/options.php/" method="post" data-trp-original-action="options.php">
            <?php
            // 未来可以在这里添加设置字段
            ?>
            <p>More advanced features (such as saving settings) will be covered in subsequent tutorials.</p>
        <input type="hidden" name="trp-form-language" value="en"/></form>
    </div>
    &lt;?php
}

After saving and refreshing the backend, you will see a new “My Plugins” menu item on the left. Click on it to access the empty settings page that we just created.

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%

Create and register a short code.

Shortcodes allow users to perform certain actions or access specific features through simple commands or inputs.[shortcode]Tags are used to insert dynamic content into articles or pages. Let’s create a short code that displays the current server time.

/**
 * 短代码处理函数
 * @param array $atts 短代码属性
 * @param string $content 短代码包裹的内容
 * @return string 返回要替换的HTML
 */
function myfp_current_time_shortcode( $atts = [], $content = null ) {
    // 设置默认属性并合并用户传入的属性
    $atts = shortcode_atts(
        array(
            'format' =&gt; 'Y-m-d H:i:s',
        ),
        $atts,
        'current_time'
    );

// 根据format属性格式化当前时间
    $current_time = date( $atts['format'] );

// 返回输出内容
    return '<div class="myfp-time"><strong>Current Time:</strong> '`. esc_html($current_time)`.'</div>'// Register the shortcode [current_time]
add_shortcode( 'current_time', 'myfp_current_time_shortcode' );

Now, you can enter text in any article, page, or widget's text box.[current_time]To display the time in the default format, or to use…[current_time format="F j, Y"]This is to display time in a custom format. WordPress will automatically invoke our code to achieve this.myfp_current_time_shortcode()A function is used to process and replace this short code.

summarize

By following this guide, you have completed the key steps in building a fully functional WordPress plugin from scratch. You have learned about the basic structure of a plugin, the importance of header comments, and you have practiced the core concept of WordPress development: the hook system. You have successfully used the hook system to integrate your plugin with other WordPress components and extend its functionality.add_action()Content has been added to the website’s front end.add_menu_page()A management backend interface has been created and is being used.add_shortcode()Short codes have been registered for use by the content editor.

Recommended Reading An Introduction to WordPress Plugin Development

This is just the starting point in the world of plugin development. From here, you can explore more complex areas, such as creating database tables to store data, and using…add_settings_section()andadd_settings_field()Build a proper options page, handle form submissions, add AJAX interactions, create custom article types and taxonomies, and follow WordPress coding standards as well as security best practices when releasing your plugin. Keep practicing and exploring, and you will be able to develop powerful and professional WordPress plugins.

FAQ Frequently Asked Questions

How many files must a plugin contain?

A plugin can contain only one main PHP file. For simple plugins, this is completely sufficient. As the functionality of a plugin becomes more complex, it is recommended to split the different functional modules into separate files (such as CSS, JavaScript, class definition files, etc.) for better code clarity and maintainability. These modules can then be organized and loaded through the main file.

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.

Why doesn’t my plugin appear in the background list?

This is usually caused by incorrect formatting of the plugin header comments or an incorrect file path. Please make sure that your main PHP file for the plugin is located directly in the specified directory./wp-content/plugins/your-plugin-folder/The files are located in the directory, and the format of the comment block at the top of each file is completely correct, especially…Plugin Name:This line is essential. After ensuring there are no errors, simply refresh the plugin page.

What is the difference between action hooks and filter hooks?

Action hooks are used to “execute a piece of code” at specific moments; they do not require a return value and are primarily used to trigger additional functions, such as adding HTML or sending emails. Filter hooks, on the other hand, are used to “modify data” and must return a value (usually the modified input data). They are mainly used to make adjustments before the content is displayed, for example, changing the title of an article or adding links to the content.

How to safely remove the added hooks?

You can use theremove_action()Orremove_filter()A function is used to remove the previously added hook. However, it is essential to ensure that the removal operation occurs after the original addition, and the priority parameter must match the one used during the initial addition.add_action()Oradd_filter()The priorities are consistent within the system. It is generally recommended to perform the removal operation when the plugin’s hooks are disabled or under specific conditions.