Shortcode Tutorial – Get Post List by Shortcode

WordPress shortcodes are square bracket strings ([ ]) that magically transform into something fascinating on the frontend. In this tutorial we will see how to use shortcodes to get post list from database.

Create a shortcode which displays a list of post when we use it inside widgets, comments or anywhere in wordpress.

We will create using a plugin. But if you want, you can do same using functions.php file of activated theme.

<?php

/*
Plugin Name:  Simple Basic Shortcode
Description: It will display a list of posts
Author: Online Web Tutor
Author URI: https://onlinewebtutorblog.com/
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Text Domain: basic-shortcode
Version: 1.0
*/

function owt_recent_posts_shortcode($atts, $content = null)
{
    global $post;

    extract(shortcode_atts(array(
        'cat'     => '',
        'num'     => '5',
        'order'   => 'DESC',
        'orderby' => 'post_date',
    ), $atts));

    $args = array(
        'cat'            => $cat,
        'posts_per_page' => $num,
        'order'          => $order,
        'orderby'        => $orderby,
    );

    $output = '';

    $posts = get_posts($args);

    foreach ($posts as $post) {

        setup_postdata($post);

        $output .= '<li><a href="' . get_the_permalink() . '">' . get_the_title() . '</a></li>';
    }

    wp_reset_postdata();

    return '<ul>' . $output . '</ul>';
}

add_shortcode('blog_posts', 'owt_recent_posts_shortcode');

Shortcode Examples

[blog_posts num="2"]

[blog_posts num="5" cat="7"]

Concept

We used here a wordpress function to read posts from database get_posts(). Retrieves an array of the latest posts, or posts matching the given conditions.

We used the created shortcode in wordpress page, [blog_posts num=”2″] It displays