How To Display WordPress Posts Using Shortcode

To display WordPress posts using shortcode, follow these steps:

  1. Open the functions.php file of your WordPress theme.
  2. Add the following code to create a shortcode that will display the posts:
//Post display shortcode
// function that runs when shortcode is called
function wpb_demo_shortcode() {

$args = array(
'post_type' => 'post', // don't forget to replace it with your custom post type name
'posts_per_page' => '3',
'publish_status' => 'published',
);

$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) :

$query->the_post() ;

$result .= '<div class="item">';
$result .= '<div class="itemname">' . get_the_title() . '</div>';
$result .= '<div class="item-desc">' . get_the_content() . '</div>';
$result .= '</div>';
endwhile;
wp_reset_postdata();
endif;
// Output needs to be return
return $result;
}
// register shortcode
add_shortcode('postdisplay', 'wpb_demo_shortcode');


  • 3. Save the file and go to the WordPress editor.
  • 4. Create a new post or page, and add the shortcode [postdisplay]

Hope this article will help you to display WordPress posts using shortcode.