Home Backend Development PHP Tutorial Develop custom WordPress plugins using PHP

Develop custom WordPress plugins using PHP

May 26, 2023 am 11:40 AM
php wordpress Plug-in development

With the development of WordPress, more and more users need to customize the functions of WordPress websites. To meet this need, developing your own WordPress plugin is a good option. In this article, we will discuss how to develop custom WordPress plugins using PHP.

First of all, let us first understand the structure of WordPress plug-in. In WordPress, plugins are implemented through a folder and must contain a specified file. This file is plugin-name.php, where "plugin-name" is the name of the plugin. In this file, we can define the name, version number, author and other information of the plug-in.

In addition to the plugin-name.php file, we can create other PHP files in the plugin folder. These files can contain code for our plugin functionality. Within our main files, we can use the add_action() and add_filter() functions to link the functionality in these files with WordPress-specific events and hooks.

Below we will use a simple plug-in example to demonstrate this process. In this plugin, we will create a simple contact form and add it to a WordPress page.

The first step is to create the plug-in folder

First create a folder named "my-contact-form" in the wp-content/plugins/ directory. This will be our plug-in the root directory.

The second step is to create the main file plugin-name.php

Create the file plugin-name.php in the my-contact-form folder. In this file, we will define the basic information of the plugin (such as name, version, author), etc. and will connect our functional code.

The following is the basic content of plugin-name.php:

<?php
/*
Plugin Name: My Contact Form
Plugin URI: http://mywebsite.com/
Description: A simple contact form plugin
Version: 1.0
Author: John Doe
Author URI: http://mywebsite.com/
*/

// Our plugin's code will go here.
Copy after login

Next, we will add some functional code, including the ability to add a contact form to the WordPress page.

When our plug-in is loaded by WordPress, the init function is executed. So we need to add the init function to the main file and add an add_shortcode function to it for adding the contact form to the WordPress page.

Here is the final plugin-name.php file:

<?php
/*
Plugin Name: My Contact Form
Plugin URI: http://mywebsite.com/
Description: A simple contact form plugin
Version: 1.0
Author: John Doe
Author URI: http://mywebsite.com/
*/

function my_contact_form_shortcode() {
    // Code to create the contact form
}

add_shortcode( 'my_contact_form', 'my_contact_form_shortcode' );
Copy after login

Now that we have created a simple contact form functionality, the way to add it to your WordPress page is to use a shortcode " [my_contact_form]".

The third step is to create the contact form function code

Now, let us create a PHP file containing the contact form. Create a file named "contact-form.php" in the my-contact-form folder and add the following code to this file:

<?php
function my_contact_form_shortcode() {

    $output = '';

    // Check if the submitted form isset
    if( isset( $_POST['my_contact_submit_button'] ) ) {
        // Sanitize the submitted data
        $name = sanitize_text_field( $_POST['my_contact_name'] );
        $email = sanitize_email( $_POST['my_contact_email'] );
        $message = esc_textarea( $_POST['my_contact_message'] );

        // Send the email
        $to = 'myemail@example.com';
        $subject = 'New Contact Form Submission';
        $body = "Name: $name 

Email: $email 

Message: $message";
        $headers = array('From: ' . $name . ' <' . $email . '>');
        wp_mail( $to, $subject, $body, $headers );

        // Set a confirmation message
        $output = '<p style="color: green;">Your message has been sent.</p>';
    }
    else {
        // Display the contact form
        $output .= '<form method="post">
            <p>
                <label for="my_contact_name">Name</label><br/>
                <input type="text" name="my_contact_name" required>
            </p>
            <p>
                <label for="my_contact_email">Email</label><br/>
                <input type="email" name="my_contact_email" required>
            </p>
            <p>
                <label for="my_contact_message">Message</label><br/>
                <textarea name="my_contact_message" required></textarea>
            </p>
            <p>
                <input type="submit" name="my_contact_submit_button" value="Submit">
            </p>
        </form>';
    }

    return $output;

}
Copy after login

This code implements a simple contact form , when the user clicks the "Submit" button, it sends the name, email, and message to the specified email address. If the submission is successful, a confirmation message will be displayed on the page.

Now, we need to edit the main file again to connect the function code in contact-form.php with WordPress. We can use the require_once() function in the init function to link them to the main file.

Here is the final plugin-name.php file:

<?php
/*
Plugin Name: My Contact Form
Plugin URI: http://mywebsite.com/
Description: A simple contact form plugin
Version: 1.0
Author: John Doe
Author URI: http://mywebsite.com/
*/

function my_contact_form_shortcode() {
  // Code to create the contact form
}

add_shortcode( 'my_contact_form', 'my_contact_form_shortcode' );

function my_contact_form_scripts() {
  wp_enqueue_style( 'my-contact-form', plugins_url( 'my-contact-form/css/style.css' ) );
}
add_action('wp_enqueue_scripts', 'my_contact_form_scripts');

require_once( plugin_dir_path( __FILE__ ) . 'contact-form.php' );
Copy after login

Now, we have successfully added the contact form functionality to WordPress. If you follow the above steps exactly, you will definitely see the new plugin in WordPress and be able to add a contact form on your page using shortcodes.

In short, developing your own WordPress plug-in can not only help you add and customize functions in WordPress, but it is also a good way to learn PHP. Hope this article helps you get started writing your own WordPress plugin!

The above is the detailed content of Develop custom WordPress plugins using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles