DEV Community

Cover image for Display the 'next 5' posts in a shortcode with Wordpress
SeanAUS120
SeanAUS120

Posted on

Display the 'next 5' posts in a shortcode with Wordpress

I like how magazines often show a little section with the next few (or related) posts halfway down the article and wanted to build this for myself to add to some Wordpress sites like Sales Tax USA.

Here's a little snippet you can add to Functions.php to achieve it. Just use [next_five_posts] as a shortcode where you want it to appear:

function next_five_posts_shortcode() {
    global $post;
    $current_post = $post->ID;
    $args = array(
        'posts_per_page' => 5,
        'post__not_in' => array($current_post),
        'offset' => 1
    );
    $next_five_posts = new WP_Query($args);
    if($next_five_posts->have_posts()) {
        $output = '<ul class="extraposts">';
        while($next_five_posts->have_posts()) {
            $next_five_posts->the_post();
            $output .= '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
        }
        $output .= '</ul><';
    } else {

    }
    wp_reset_postdata();
    return $output;
}
add_shortcode('next_five_posts', 'next_five_posts_shortcode');

Enter fullscreen mode Exit fullscreen mode

Currently in use at:
Wild Posting
Gorilla Printing
Wine N Liquor
UCG
ReWorder
PLA
SignsCity
PluginRush
SalesTaxUSA
WineVybe
Sales Tax API

Top comments (0)