How to Add Left and Right Floating Navigation Buttons to WordPress Posts

wordpress floating buttonsnext previous post navigationwordpress sidebar buttonscustom post navigationwordpress js navigation
Published·Modified·

While browsing articles online, I came across a small feature: two fixed floating buttons on the left and right sides used to switch between the previous and next articles. This is very intuitive and enhances user experience. Here, I will share my code.

1. Upload Image Assets

Save the following two images locally, then upload them to your media library and obtain their corresponding URL addresses.

right_64 left_64

2. Add CSS Styles

Add the following CSS styles to the style.css file in your theme directory. If you use Qiniu Cloud Storage, please clear the cache on Qiniu, otherwise it will not take effect. Alternatively, you can add the code directly to the header.php file in your theme directory, placing it before </head>.

#art_left{
    position:fixed;
    top:50%;
    left:10px;
    margin-top:-32px;
}
#art_right{
    position:fixed;
    top:50%;
    right:10px;
    margin-top:-32px;
}

3. Add JavaScript Function

Add the following code to the single.php page in your theme directory at an appropriate location. Replace the image addresses with your own URLs, following the method in Step 1.

<!-- Previous and Next Page Navigation -->
<div class="prev" id = "prev" style = "display:none;"><?php previous_post_link('« %link') ?></div>
<div class="next" id = "next" style = "display:none;"><?php next_post_link('%link »') ?></div>
<div id = "art_left">
    <a href = "javascript:;" onclick = "jump('p');">
        <img src = "Your Image URL" />
    </a>
</div>
<div id = "art_right">
    <a href = "javascript:;" onclick = "jump('n');"><img src = "Your Image URL" /></a>
</div>
<script>
    // Declare global variables
    var prev;
    var next;
    // Get corresponding URLs
    $(document).ready(function(){
        prev = $("#prev a").attr("href");
        next = $("#next a").attr("href");
    });
    // Call method to jump
    function jump(re) {
        if(re == 'p') {
            window.location.href = prev;
        }
        if(re == 'n') {
            if(next == null) {
                alert('No more!');
                return false;
            }
            else{
                window.location.href = next;
            }
        }
    }
</script>
<!-- Previous and Next Page Navigation END -->

With the three steps above, you can switch between the previous and next articles using fixed floating buttons on the left and right. You can refer to the left and right sides of my blog posts for the effect. Adding the code above may require some basic knowledge of HTML; otherwise, errors may occur. If you encounter any problems, you can contact me for help.