How to Use Keyboard Arrow Keys for WordPress Posts Navigation?


Sometimes, you might want to provide visitors to navigate to next or previous posts quickly by using keyboard arrow keys. You might place the navigate links in the post as well, but the keyboard is always faster than a mouse!

The core functions we rely on when developing this feature are: get_adjacent_post, get_previous_posts_page_link and get_next_posts_page_link.

If you want to exclude the pages (e.g. homepage, categories, tags, archieves), you can use get_adjacent_post to get the next/previous post links.

Add the following PHP Code to your child-theme single.php template file:

1
2
3
4
5
6
7
8
document.onkeydown = function (e) {
    var e = e || event, 
    keycode = e.which || e.keyCode; 
    if (keycode == 37 || keycode == 33)
        location = "<?php echo get_permalink(get_adjacent_post()); ?>";
    if (keycode == 39 || keycode == 34)
        location = "<?php echo get_permalink(get_adjacent_post()); ?>";
}
document.onkeydown = function (e) {
    var e = e || event, 
    keycode = e.which || e.keyCode; 
    if (keycode == 37 || keycode == 33)
        location = "<?php echo get_permalink(get_adjacent_post()); ?>";
    if (keycode == 39 || keycode == 34)
        location = "<?php echo get_permalink(get_adjacent_post()); ?>";
}

If the pages are also included, you need to use get_previous_posts_page_link and get_next_posts_page_link to retrieve the neighbour posts/pages.

1
2
3
4
5
6
7
8
document.onkeydown = function (e) {
    var e = e || event,
    keycode = e.which || e.keyCode; 
    if (keycode == 37 || keycode == 33)
        location = "<?php echo get_previous_posts_page_link(); ?>";
    if (keycode == 39 || keycode == 34)
        location = "<?php echo get_next_posts_page_link(); ?>";
}
document.onkeydown = function (e) {
    var e = e || event,
    keycode = e.which || e.keyCode; 
    if (keycode == 37 || keycode == 33)
        location = "<?php echo get_previous_posts_page_link(); ?>";
    if (keycode == 39 || keycode == 34)
        location = "<?php echo get_next_posts_page_link(); ?>";
}

–EOF (The Ultimate Computing & Technology Blog) —

Arrow-keys How to Use Keyboard Arrow Keys for Wordpress Posts Navigation? php tricks wordpress

Arrow-keys

GD Star Rating
loading...
410 words
Last Post: How to Draw a Heart using CSS3?
Next Post: How to Test Element in Array (In Array) and Array Contains in Javascript?

The Permanent URL is: How to Use Keyboard Arrow Keys for WordPress Posts Navigation?

Leave a Reply