How to create a widget or plugin to add custom content to my website?

Yes you can create a widget and set the content from the back-end. You can also do it by a plugin. But since you asked for a widget, I did write a full widget for you.

The code is plenty self explanatory, since I added details for every line. I didn’t copy your code to it because I was unsure about what you want, but after having a look at the code, you should be able to do it easily.

// Initiate our widget, when WordPress is firing the widgets
add_action( 'widgets_init', 'my_custom_widget' );
function my_custom_widget() {
    // Some custom name for the widget
    register_widget( 'create_my_widget' );  
}

// Extend the WP_Widget class
class create_my_widget extends WP_Widget {

    // Let's set a name and ID for our widget
    function __construct() {
        parent::__construct(
            'create_my_widget', // Widget's ID
            __('My Custom Widget', 'photogram'), // Widget's Title in the back-end
            array( 'description' => __( 'Widget Description in the admin panel', 'photogram' ), ) 
        );
    }

    // This is the front-end of our widget
    public function widget( $args, $instance ) {
        // Filter for our widget's title, in case we need to change it later
        $title = apply_filters( 'widget_title', $instance['title'] );
        // This is an example value to use in our widget
        $value = apply_filters( 'widget_title', $instance['value'] );
        // If widget has no data, then do nothing
        if(!isset($value)) return; 
        // We output the widget's title and "before" argument
        echo $args['before_widget'];
        if ( ! empty( $title ) )
        echo $args['before_title'] . $title . $args['after_title'];
        // Now, here is the place to code and output the actual HTML

        echo 'Your HTML content goes here';

        // Now, we close the widget
        echo $args['after_widget'];
    }

    // This is to add the data in the back-end
    public function form( $instance ) {
        // Set the title of our widget, if it's not set. Remember, this is for front-end
        if ( isset( $instance[ 'title' ] ) ) {
            $title = $instance[ 'title' ];
        } else {
            $title = __( 'My Widget Title', 'photogram' );
        }

        //Remember the value? We give it a default value if it's not set. This happens when you save a widget
        if ( isset( $instance[ 'value' ] ) ) {
            $value = $instance[ 'value' ];
        } else {
            $value="Some default value";
        } ?>
        <!-- Now, the place to add content to our widget in the back-end. The first field is for title, the second one is... whatever we want. -->
        <p>
            <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" />
        </p>
        <p>
            <label for="<?php echo $this->get_field_id( 'value' ); ?>"><?php _e( 'Value:' ); ?></label> 
            <input id="<?php echo $this->get_field_id( 'value' ); ?>" name="<?php echo $this->get_field_name( 'value' ); ?>" type="text" value="<?php echo esc_attr( $value ); ?>" />
        </p>
        <?php 
    }
    // Updating widget replacing old instances with new
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';
        $instance['value'] = ( ! empty( $new_instance['value'] ) ) ? strip_tags( $new_instance['value'] ) : '';
        return $instance;
    }
}

Now, your scripts!

We managed to output some HTML and add some data to it by using a widget. Now, to add your scripts and style to your website, you should use wp_enqueue_scripts. Store your scripts in some js file, and your styles in some CSS file. Then, enqueue them:

add_action('wp_enqueue_scripts','my_widget_scripts');
function my_widget_scripts(){
    // Enqueue your styles
    wp_enqueue_style('my-styles',get_template_directory_uri().'/my-style.css');
    // And your script
    wp_enqueue_script('my-scripts',get_template_directory_uri().'my-script.js');
}

Plugin Approach

Time to do this by a plugin. To do so, we need two different things:

  1. An option page to store our data
  2. A function to return the data to the template

We can create an option page by using add_options_page():

if ( ! class_exists( 'my_Custom_plugin' ) ) {
    class my_Custom_plugin {
        public function __construct() {
            // We only need to register the admin panel on the back-end
            if ( is_admin() ) {
                add_action( 'admin_menu', array( 'my_Custom_plugin', 'my_plugin_add_admin_menu' ) );
                add_action( 'admin_init', array( 'my_Custom_plugin', 'custom_plugin_register_settings' ) );
            }
        }
        // Returns all plugin options 
        public static function get_my_custom_plugin() {
            return get_option( 'my_custom_plugin' );
        }
        // Returns single plugin option
        public static function my_plugin_get_theme_option_value( $id ) {
            $options = self::get_my_custom_plugin();
            if ( isset( $options[$id] ) ) {
                return $options[$id];
            }
        }
        // Add sub menu page
        public static function my_plugin_add_admin_menu() {
            add_options_page(
                esc_html__( 'Plugin Options', 'text-domain' ),
                esc_html__( 'Plugin Options', 'text-domain' ),
                'manage_options',
                'plugin-options-slug',
                array( 'my_Custom_plugin', 'plugin_create_admin_page' )
            );
        }
        // Register a setting and its sanitization callback.
        public static function custom_plugin_register_settings() {
            register_setting( 'my_custom_plugin', 'my_custom_plugin', array( 'my_Custom_plugin', 'custom_plugin_sanitize' ) );
        }
        // Sanitization callback
        public static function custom_plugin_sanitize( $options ) {
            // If we have options lets sanitize them
            if ( $options ) {
                // Checkbox sanitize
                if ( ! empty( $options['checkbox_input'] ) ) {
                    $options['checkbox_input'] = 'on';
                } else {
                    $options['checkbox_input'] = 'off'; 
                }
                // Input sanitize
                if ( ! empty( $options['text_input'] ) ) {
                    $options['text_input'] = sanitize_text_field( $options['text_input'] );
                } else {
                    unset( $options['text_input'] ); // Remove from options if empty
                }
            }
            // Return sanitized options
            return $options;
        }
        // Settings page output
        public static function plugin_create_admin_page() { ?>
            <div class="wrap">
                <div class="page-header">
                    <h1><?php esc_html_e( 'Plugin Options', 'text-domain' ); ?></h1>
                </div>
                <?php settings_errors(); ?>
                <form method="post" action="options.php">
                    <?php settings_fields( 'my_custom_plugin' ); ?>
                    <div class="panel panel-default">
                        <table class="form-table">
                            <tbody><?php
                                // This is a sample checkbox ?>
                                <tr>
                                    <th scope="row">
                                        <?php esc_html_e( 'Sample Checkbox', 'text-domain' ); ?>
                                    </th>
                                    <td>
                                        <?php $value = self::my_plugin_get_theme_option_value( 'checkbox_input' ); ?>
                                        <label for="sample-checkbox"><?php esc_html_e( 'Sample Checkbox', 'text-domain' ); ?></label>
                                        <input id="sample-checkbox" type="text" name="my_custom_plugin[checkbox_input]" <?php checked( $value, 'on' ); ?> />
                                    </td>
                                </tr><?php
                                // And this is a sample text input ?>
                                <tr>
                                    <th scope="row">
                                        <?php esc_html_e( 'Sample Text', 'text-domain' ); ?>
                                    </th>
                                    <td>
                                        <?php $value = self::my_plugin_get_theme_option_value( 'text_input' ); ?>
                                        <label for="sample-input"><?php esc_html_e( 'Sample Checkbox', 'text-domain' ); ?></label>
                                        <input type="text" name="my_custom_plugin[text_input]" value="<?php echo esc_attr( $value ); ?>"> 
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    <?php submit_button(); ?>
                </form>
            </div>
        <?php }
    }
}
new my_Custom_plugin();
// Helper function to use in theme to return a theme option value
function get_my_custom_plugin_value( $id = '' ) {
    return my_Custom_plugin::my_plugin_get_theme_option_value( $id );
}

In the above example I have included a sample checkbox and text input for you. You can change it with whatever you want. Textarea, select, and more. After we write our class, there will be a new option added in the back-end. We will have a text input and a checkbox which we can modify. After saving the data, it can be retrieved by using this:

get_my_custom_plugin_value($id);

The id must be equal to input’s name, which in this case it text_input or checkbox_input. This data will be used later to shape the HTML.

Now the second part, is creating a plugin to use this code in it. Simply create a blank php file, name it whatever you want, and add this piece of code to it:

<?php
/*
Plugin Name: Sample Plugin
Description: Some description
Author: Your name
Version: 1.0
Author URI: Your website URL
*/

// Now we create our HTML

function create_my_html(){
    // Write your HTML structure here. Whenever you need a value,
    // use get_my_custom_plugin_value() to add it to your HTMl.

} 

// After creating the HTML, you should include the class in your plugin,
// to add the options. It can be pasted here.

// Now, enqueue your CSS and JS files, the way I mentioned above
?>

Everything is done. You can now call create_my_html(); in your templates, to output the HTML wherever you want. Don’t forget to use echo, if you are returning the data instead of printing it. Also, use it in conjunction with function_exists() to make sure your theme never breaks if the plugin is disabled:

if (function_exists(create_my_html())) {
    echo create_my_html();
}

Abracadabra!

Expecting more? Sorry to disappoint you. That’s all 🙂

Leave a Comment