If you’re looking to enhance the navigation of your WordPress website, adding a “Back to Top” button is a simple yet effective solution. It improves the user experience, especially on long pages. In this tutorial, we’ll go through how to add this feature using a shortcode, without the need to edit your theme’s functions.php
file directly. Instead, we’ll use a safer method: a Code Snippets plugin.
Why Avoid Direct functions.php
Edits?
Editing the functions.php
file directly can lead to issues if not done correctly. A single error can make your website inaccessible. However, by using a Code Snippets plugin, you can add the same piece of code with less risk. It also keeps your custom code organized and easy to manage.
Step 1: Install a Code Snippets Plugin
Before we start, install a plugin for managing code snippets. There are several available, such as “Code Snippets” by Code Snippets Pro. Install and activate your chosen plugin.
Step 2: Create the Shortcode
Go to the newly added ‘Snippets’ menu in your admin dashboard. Create a new snippet with the following PHP code:
function back_to_top_shortcode() { wp_enqueue_script('back-to-top-js'); return '<a href="#top" id="back-to-top" title="Back to top">↑</a>'; } add_shortcode('back_to_top', 'back_to_top_shortcode');
Step 3: Enqueue the JavaScript
Add another snippet for the JavaScript. This will control the button’s appearance and scroll behavior:
function enqueue_back_to_top_script() { wp_enqueue_script('back-to-top-js', get_template_directory_uri() . '/js/back-to-top.js', array('jquery'), null, true); } add_action('wp_enqueue_scripts', 'enqueue_back_to_top_script');
Create the back-to-top.js
file in the js
directory of your child theme folder and add the JavaScript code provided earlier in this post.
Step 4: Add the CSS
Now, add a snippet for the CSS to style your “Back to Top” button:
#back-to-top { display: none; position: fixed; bottom: 20px; right: 20px; background: #666; color: #ffffff; padding: 10px 15px; font-size: 20px; text-decoration: none; border-radius: 5px; z-index: 100; } #back-to-top:hover { background: #555; }
You can add this CSS directly into your theme’s custom CSS section, or use the ‘Custom CSS’ feature of the Code Snippets plugin if it provides one.
Step 5: Usage
Insert the shortcode [back_to_top]
in any page or post where you wish the button to appear. Or, you could automatically append it to every page by using another snippet:
add_action('wp_footer', 'back_to_top_shortcode');
Conclusion
Adding a “Back to Top” button to your WordPress site enhances usability and can be done easily with a shortcode. By using a Code Snippets plugin, you ensure that your website remains stable and that your custom code is not lost during theme updates. Implement this user-friendly feature today, and improve your site’s navigation with just a few clicks!