WordPress

Back To Top WordPress Plugin

In a previous tutorial I wrote about how you can use jQuery to create a Scroll back to top button.

jQuery Back To Top

In this tutorial we are going to create a WordPress plugin that adds scroll back to top link to your website. You will learn how to create the plugin to handle this and settings to change the position of the link and text on the link.

You can either work your way through this tutorial to create the plugin or download the complete plugin at the end of the tutorial.

Creating The Plugin

The first thing we need to do is create a new WordPress plugin, to do this create a new folder in your /wp-content/plugins folder you can call it whatever you want but I'm going to call it paulund-back-to-top.

Inside this folder create new file called paulund-back-to-top.php, this is going to be the main plugin file and will be used by WordPress to know the display this plugin.

Inside this main plugin file you need to add comments to the top of the file that defines the title and description of the plugin.

/**
 * Paulund back to top plugin
 *
 * Plugin Name:       Paulund Back To Top
 * Plugin URI:        http://www.paulund.co.uk
 * Description:       Add a link to your site for a quick link back to the top of the page
 * Version:           1.0.0
 * Author:            Paulund
 * Author URI:        http://www.paulund.co.uk
 * Text Domain:       text-domain
 * License:           GPLv2 or later
 * License URI:       http://www.gnu.org/licenses/gpl-2.0.html
 * Domain Path:       /languages
 */

This plugin is going to have different behaviour depending on if you are viewing it in the admin area or on the frontend.

On the admin area we need to add a new menu item and a settings page so that the admin of the site can change the position and text of the back to top link.

On the frontend of the site the plugin will need to add a new Javascript file, CSS file and text the user can click to return to the top of the page. As we don't want these to be added in the admin area then we can split up the functionality into admin functionality and frontend functionality.

// Check if the plugin is loaded in the admin area
if(is_admin())
{
    // Load admin class
    require_once dirname(__FILE__) . '/admin/admin-back-to-top.php';
    new Admin_Back_To_Top();
} else {
    // Load frontend class
    require_once dirname(__FILE__) . '/plugin/frontend-back-to-top.php';
    new Frontend_Back_To_Top();
}

Create The Admin Area Class

Inside your plugin folder create a new folder called admin, then create a new file called admin-back-to-top.php. This is where we are going to have all the functionality for the admin area.

First we need to create a new menu item on the admin settings sub menu by using the function add_options_page().

<?php
/**
 * The admin area back to top class
 *
 * Creates the menu for the settings
 * Creates the settings page
 * Handles the post data of the form
 */
class Admin_Back_To_Top
{
    /**
     * Const for the name of the plugin
     * Used on settings page and menu title
     */
    const plugin_name = 'Paulund Back To Top';

    /**
     * Const for the plugin slug used for the settings page
     */
    const plugin_slug = 'paulund-back-to-top';

    /**
     * Admin_Back_To_Top constructor.
     */
    public function __construct()
    {
        // Add the menu item to the admin menu
        add_action('admin_menu', array($this, 'add_settings_menu'));
    }

    /**
     * Adds the settings menu to the admin menu
     */
    public function add_settings_menu()
    {
        // Add the menu item to the settings sub menu
        add_options_page(
            self::plugin_name,
            self::plugin_name,
            'manage_options',
            self::plugin_slug,
            array($this, 'display_settings_page')
        );
    }
}

The above code will add a new link to the settings menu called Paulund Back To Top, clicking on this link will take you to a new page at the URL of /wp-admin/options-general.php?page=paulund-back-to-top.

The method that is called when you go to this URL is called display_settings_page so we need to create a new method for this inside the admin class.

/**
 * Displays the settings page with all the settings options
 */
public function display_settings_page()
{

}

On the settings page we want to create 3 different settings for the back to top link.

  • Decide if the link is turned on or off.
  • The position for the back to top link.
  • The text to use on the link.

paulund-back-to-top-admin

/**
     * Displays the settings page with all the settings options
     */
    public function display_settings_page()
    {
        // Get the current settings
        $currentSettings = $this->get_settings();
        ?>
        <div id="wrap">
            <h1><?php echo self::plugin_name; ?></h1>

            <form method="post" action="options-general.php?page=<?php echo self::plugin_slug; ?>">
                <table>
                    <tr>
                        <td>Turn On Back To Top</td>
                        <td><input type="checkbox" name="paulund-back-to-top-on" value="1" <?php checked(1, $currentSettings['paulund-back-to-top-on']); ?>></td>
                    </tr>
                    <tr>
                        <td>Link Position</td>
                        <td><select name="paulund-back-to-top-position">
                                <option value="">Select Position</option>
                                <option value="top-left" <?php selected('top-left', $currentSettings['paulund-back-to-top-position']); ?>>Top Left</option>
                                <option value="top-right" <?php selected('top-right', $currentSettings['paulund-back-to-top-position']); ?>>Top Right</option>
                                <option value="bottom-left" <?php selected('bottom-left', $currentSettings['paulund-back-to-top-position']); ?>>Bottom Left</option>
                                <option value="bottom-right" <?php selected('bottom-right', $currentSettings['paulund-back-to-top-position']); ?>>Bottom Right</option>
                            </select></td>
                    </tr>
                    <tr>
                        <td>Back To Top Text</td>
                        <td><input type="text" name="paulund-back-to-top-text" value="<?php echo $currentSettings['paulund-back-to-top-text']; ?>"></td>
                    </tr>
                </table>

                <p class="submit">
                    <input type="submit" name="paulund-back-to-top-settings" class="button-primary" value="<?php _e('Save Changes') ?>" />
                </p>
            </form>
        </div>
        <?php
    }

Above is the full code we are going to use for the settings on the page. It's important to know that there are two ways in WordPress to create settings for your plugins, you can either build it yourself like we have done in this plugin or you can use the WordPress settings API.

The preferred option for settings is to use the Settings API but in this plugin as we only have 3 options then I'm opting to just use the simpler option of creating the settings without the API. The benefit you get with the Settings API is the reusability of code and validation is much easier to handle, but we only have 3 settings it's not needed.

As you can see from the first line inside the display_settings_page() function is

$currentSettings = $this->get_settings();

This is going to be populated with default values or the values from the database.

Getting And Storing The Settings

The next method we need to create is the method that will get the back to top settings and also store this form values in the database.

First we use the get_option() function to get the database values we then we check to see if there are any post values. If there are no post values then this function will simply return the settings from the database.

If there are post values from the form there we can construct an array with the values from the form and validate this using the sanitize_text_field() function.

/**
     * Get the settings from the data stored in the options table
     *
     * @return array
     */
    public function get_settings()
    {
        // Get the current settings from the options table
        $currentSettings = get_option(self::plugin_slug);

        // Handle the post data of the form
        if(!empty($_POST['paulund-back-to-top-settings']))
        {
            // Check if link is turned on
            if(!empty($_POST['paulund-back-to-top-on']))
            {
                $currentSettings['paulund-back-to-top-on'] = true;
            } else {
                $currentSettings['paulund-back-to-top-on'] = false;
            }

            // Set the position of the link
            if(!empty($_POST['paulund-back-to-top-position']))
            {
                $currentSettings['paulund-back-to-top-position'] = sanitize_text_field( $_POST['paulund-back-to-top-position'] );
            }

            // Set the text of the link
            if(!empty($_POST['paulund-back-to-top-text']))
            {
                $currentSettings['paulund-back-to-top-text'] = sanitize_text_field( $_POST['paulund-back-to-top-text'] );
            }

            // Update the settings in the options table
            update_option(self::plugin_slug, $currentSettings);
        }

        // Set the default options of the form
        if(empty($currentSettings))
        {
            $currentSettings['paulund-back-to-top-on'] = true;
            $currentSettings['paulund-back-to-top-position'] = '';
            $currentSettings['paulund-back-to-top-text'] = 'Back To Top';
        }

        // Return an array of the settings either from the options table or default settings
        return $currentSettings;
    }

The above will process the form values and store these in the database so that we can use them on the frontend of the website.

Create The Frontend Class

As the admin area and storing of the data is complete we can now create the frontend class to add the Javascript, stylesheet and text to the page for the user to click on the link to return to the top of the page.

First we create a class that will get the options of the plugin settings from the database by using the get_option() function in the constructor to check if the plugin is turned on or off. If the admin user has decided to turn the plugin settings off then we don't need to add the Javascript and CSS files and we don't need to add the link to the page.

/**
 * The frontend class will add javascript and CSS file to the website
 *
 * It will then add text to the bottom of the page which you can use to scroll back to the top of the page
 */
class Frontend_Back_To_Top
{
    /**
     * Store the settings from the admin area
     *
     * @var array
     */
    private $settings;

    /**
     * Frontend_Back_To_Top constructor.
     */
    public function __construct()
    {
        // Get the settings of the back to top page
        $this->settings = get_option('paulund-back-to-top');

        // Check to see if the back to top link is turned on
        if(!empty($this->settings['paulund-back-to-top-on']) && $this->settings['paulund-back-to-top-on'] === true)
        {
            // Add the js and css files to the page
            add_action( 'wp_enqueue_scripts', array($this, 'add_styles_and_script'));

            // Add the HTML to the foot of the page
            add_action( 'wp_footer', array($this, 'add_back_to_top_text'));
        }
    }
}

As you can see from the code above we check the settings and then add the actions for wp_enqueue_scripts and wp_footer.

Add Styles And Javascript To The Page

Below is the function that is used to add the Javascript and stylesheets to the page by using the wp_enqueue_script and wp_enqueue_style functions.

As you can see from the wp_enqueue_script function we have a 3rd parameter of array('jquery'), which is a dependency on jQuery as we are going to use jQuery to add an animation scroll to the top of the page.

/**
     * Add styles and javascript to the page
     */
    public function add_styles_and_script()
    {
        // Add JS file
        wp_enqueue_script( 'paulund-back-to-top-js', plugin_dir_url( __FILE__ ) . 'assets/js/paulund-back-to-top.js', array('jquery') );

        // Add CSS file
        wp_enqueue_style( 'paulund-back-to-top-css', plugin_dir_url( __FILE__ ) . 'assets/css/paulund-back-to-top.css' );
    }

Javascript File

Create a new Javascript file in the same location as you are loading the Javascript file and paste in the following code. This will create a new namespace of back_to_top and place a function which adds events to the browser page to perform the animation.

First we add a scroll event to the browser window, so that on the scroll event we will run a function, this function checks to see the scroll position, if it is more than 100 pixel high then we fade in the back to top link. If the page is less than 100 pixel high that we can hide the back to top link as it's not needed anymore.

Then we can add a click event to the back to top link which will do the animated scroll to top using the jQuery animate function.

jQuery(document).ready(function(  )
{
    back_to_top.init();
});

var back_to_top =
{
    init: function(){
        /**
         * When the scroll is move than 100 pixel down the page then fade in the link
         */
        jQuery(window).scroll(function(){
            if (jQuery(this).scrollTop() > 100) {
                jQuery('.paulund-back-to-top').fadeIn();
            } else {
                jQuery('.paulund-back-to-top').fadeOut();
            }
        });

        /**
         * On the click event of the link scroll back to the top of the page
         */
        jQuery('.paulund-back-to-top').on('click', function(){
            jQuery('html, body').animate({scrollTop : 0},800);
            return false;
        });
    }
};

Styling The Back To Top Link

Next we can style the back to top link so that we can have different locations on the page as per our settings in the admin area.

The first CSS class is the paulund-back-to-top class which set the position of the link as fixed so that it stays in the same position on the page, we add a pointer cursor to the link so users know it's clickable, and hide the link by default so we can fade it in when the user scrolls past 100 pixels.

Next we set up the 4 position settings of and indent the link from the edge of the page.

.paulund-back-to-top
{
    position: fixed;
    cursor: pointer;
    display: none;
}

.position-top-left
{
    top: 2em;
    left: 2em;
}

.position-top-right
{
    top: 2em;
    right: 2em;
}

.position-bottom-left
{
    bottom: 2em;
    left: 2em;
}

.position-bottom-right
{
    bottom: 2em;
    right: 2em;
}

Add back To Top Link

With the Javascript and stylesheet files added to the page we can now add the HTML the user clicks to return to the top of the page.

To add this we used the wp_footer action that should be placed on your theme at the bottom of the page, we then need to inject some HTML into this function which will output on the page.

This starts with a DIV that has a CSS class of paulund-back-to-top that will set the fixed position and then use the settings of the plugin (which we collected in the constructor) and place the position class in attribute.

Inside this DIV we can echo the text from the settings page to show the user they can click here to return to the top of the page.

/**
     * Add the back to top text to the page
     */
    public function add_back_to_top_text()
    {
        ?>
        <div class="paulund-back-to-top <?php if(!empty($this->settings['paulund-back-to-top-position'])){
            echo esc_attr('position-' . $this->settings['paulund-back-to-top-position']);
        } ?>">
            <?php echo esc_html($this->settings['paulund-back-to-top-text']); ?>
        </div>
        <?php
    }

This is all the code you will need to add a WordPress back to top plugin to your site which can be fully customised in the admin area to change the text and position of the link on your site.

Back to top ^

Join Paulund

  • Get access to 100s of premium tutorials and downloadable content
  • Members content consists of Premium WordPress plugins, CSS packages, jQuery packages, tutorial demo files and templates for 100s of web development tutorials
  • In-depth development tutorials
  • Priority tutorial requests
  • Priority email development support
  • No ads

Here at Paulund you'll find Web Development tutorials and snippets focusing mainly on PHP, WordPress and CSS. Members will get access to premium tutorials that go into more detail about development with these languages. You will also get access to downloadable premium content based on the tutorial.

Join Paulund

Leave a Reply

Your email address will not be published. Required fields are marked *