App Coding
App Coding Guide


Building Simple WordPress Plugins: A Perfect Training Project

Posted on

If you're looking to sharpen your WordPress development skills, there's no better way to start than by building your own plugin. Simple, minimalistic plugins not only provide a great learning experience but also add practical functionalities to your site. In this blog post, we'll explore a training project that involves creating four different plugins, each contained within a single PHP file. These plugins will help you understand the basics of WordPress plugin development, including how to use hooks, shortcodes, widgets, and admin options.

Why Build Simple WordPress Plugins?

Developing WordPress plugins offers a hands-on approach to learning PHP and understanding the inner workings of WordPress. By creating a plugin, you get to explore key concepts such as actions, filters, shortcodes, widgets, and the WordPress database API. Moreover, these plugins are practical tools that can enhance your website's functionality and provide a sense of accomplishment as you see your code come to life.

Plugin 1: Custom Welcome Message

Our first plugin will display a custom welcome message to visitors. This message can be configured through the WordPress admin panel, allowing for easy customization.

<?php
/*
Plugin Name: Custom Welcome Message
Description: Displays a custom welcome message.
Version: 1.0
Author: Your Name
*/

// Function to display the welcome message
function display_welcome_message() {
    $message = get_option('custom_welcome_message', 'Welcome to our website!');
    echo "<p style='text-align: center; font-size: 20px;'>$message</p>";
}
add_action('wp_footer', 'display_welcome_message');

// Admin menu to configure the welcome message
function custom_welcome_message_menu() {
    add_options_page('Custom Welcome Message', 'Welcome Message', 'manage_options', 'custom-welcome-message', 'custom_welcome_message_options');
}
add_action('admin_menu', 'custom_welcome_message_menu');

// Function to display the options page
function custom_welcome_message_options() {
    if (isset($_POST['custom_welcome_message'])) {
        update_option('custom_welcome_message', sanitize_text_field($_POST['custom_welcome_message']));
        echo '<div class="updated"><p>Message saved.</p></div>';
    }
    $message = get_option('custom_welcome_message', 'Welcome to our website!');
    echo '<div class="wrap">
            <h2>Custom Welcome Message</h2>
            <form method="post" action="">
                <label for="custom_welcome_message">Message:</label>
                <input type="text" id="custom_welcome_message" name="custom_welcome_message" value="' . esc_attr($message) . '" size="50">
                <input type="submit" value="Save" class="button-primary">
            </form>
          </div>';
}
?>

This plugin demonstrates how to use WordPress hooks (add_action) and create an admin settings page. The welcome message is displayed in the footer of your site and can be updated through the settings page.

Plugin 2: Recent Posts Shortcode

Next, we'll create a plugin that adds a shortcode to display recent posts. This is useful for including a list of recent posts on any page or post.

<?php
/*
Plugin Name: Recent Posts Shortcode
Description: Adds a shortcode to display recent posts.
Version: 1.0
Author: Your Name
*/

// Function to handle the shortcode
function recent_posts_shortcode($atts) {
    $atts = shortcode_atts(array('count' => 5), $atts, 'recent-posts');
    $query = new WP_Query(array('posts_per_page' => $atts['count']));
    $output = '<ul>';
    while ($query->have_posts()) {
        $query->the_post();
        $output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
    }
    $output .= '</ul>';
    wp_reset_postdata();
    return $output;
}
add_shortcode('recent-posts', 'recent_posts_shortcode');
?>

This plugin introduces shortcodes, which allow you to embed dynamic content into your posts and pages with ease. The recent_posts_shortcode function queries the most recent posts and generates an unordered list of their titles and links.

Plugin 3: Simple Contact Form

Our third plugin adds a basic contact form to your site. Submissions are sent to the admin email, making it a practical tool for collecting visitor feedback.

<?php
/*
Plugin Name: Simple Contact Form
Description: Adds a simple contact form.
Version: 1.0
Author: Your Name
*/

// Function to display the contact form
function simple_contact_form() {
    $output = '<form method="post" action="">
                  <p><label for="name">Name:</label><br>
                  <input type="text" name="name" required></p>
                  <p><label for="email">Email:</label><br>
                  <input type="email" name="email" required></p>
                  <p><label for="message">Message:</label><br>
                  <textarea name="message" required></textarea></p>
                  <p><input type="submit" name="submit" value="Send"></p>
               </form>';
    return $output;
}
add_shortcode('simple-contact-form', 'simple_contact_form');

// Function to handle form submission
function handle_contact_form_submission() {
    if (isset($_POST['submit'])) {
        $name = sanitize_text_field($_POST['name']);
        $email = sanitize_email($_POST['email']);
        $message = sanitize_textarea_field($_POST['message']);
        $to = get_option('admin_email');
        $subject = 'New Contact Form Submission';
        $headers = 'From: ' . $name . ' <' . $email . '>';
        wp_mail($to, $subject, $message, $headers);
        echo '<p>Thank you for your message!</p>';
    }
}
add_action('wp', 'handle_contact_form_submission');
?>

This plugin highlights how to create a form, handle form submissions, and send emails using wp_mail. The contact form can be embedded anywhere on your site using the [simple-contact-form] shortcode.

Plugin 4: Random Quote Widget

Finally, we'll create a widget that displays a random quote. Quotes can be managed through the admin panel, making this a versatile and fun addition to your site.

<?php
/*
Plugin Name: Random Quote Widget
Description: Displays a random quote.
Version: 1.0
Author: Your Name
*/

class Random_Quote_Widget extends WP_Widget {
    function __construct() {
        parent::__construct('random_quote_widget', 'Random Quote Widget');
    }

    public function widget($args, $instance) {
        $quotes = get_option('random_quotes', array('Quote 1', 'Quote 2', 'Quote 3'));
        $quote = $quotes[array_rand($quotes)];
        echo $args['before_widget'] . $args['before_title'] . 'Random Quote' . $args['after_title'];
        echo '<p>' . esc_html($quote) . '</p>';
        echo $args['after_widget'];
    }

    public function form($instance) {
        // No form needed for this widget
    }

    public function update($new_instance, $old_instance) {
        return $new_instance;
    }
}

function register_random_quote_widget() {
    register_widget('Random_Quote_Widget');
}
add_action('widgets_init', 'register_random_quote_widget');

// Admin menu to manage quotes
function random_quote_menu() {
    add_options_page('Random Quotes', 'Random Quotes', 'manage_options', 'random-quotes', 'random_quote_options');
}
add_action('admin_menu', 'random_quote_menu');

// Function to display the options page
function random_quote_options() {
    if (isset($_POST['random_quotes'])) {
        update_option('random_quotes', array_map('sanitize_text_field', $_POST['random_quotes']));
        echo '<div class="updated"><p>Quotes saved.</p></div>';
    }
    $quotes = get_option('random_quotes', array('Quote 1', 'Quote 2', 'Quote 3'));
    echo '<div class="wrap">
            <h2>Random Quotes</h2>
            <form method="post" action="">
                <label for="random_quotes">Quotes (one per line):</label>
                <textarea id="random_quotes" name="random_quotes" rows="10" cols="50">' . implode("\n", $quotes) . '</textarea>
                <input type="submit" value="Save" class="button-primary">
            </form>
          </div>';
}
?>

This plugin introduces the concept of widgets, which are a powerful way to add dynamic content to your site's sidebar or other widget-ready areas. It also shows how to create an admin interface for managing the quotes.

Building simple WordPress plugins is an excellent way to dive into WordPress development. These four examples cover essential aspects of plugin development and provide practical tools that can enhance any WordPress site. By following these examples and experimenting with your own ideas, you'll gain valuable experience and confidence in your coding abilities. So, fire up your code editor, start with these plugins, and let your creativity flow! Happy coding!