Last two posts were about creating a WordPress shortcode and a WordPress page template, I’m going to mix these two and create a shortcode to display the page template I created in my previous post.
I’ve removed header and footer from the template code (taken from the previous posts) and edited the page-onedemo.php file as follows –
<?php
/*
Template Name: One Demo Template
*/
?>
<?php $myposts = get_posts();
foreach ($myposts as $post): ?>
<li><?php the_time('d/m/y') ?>: <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endforeach; ?>
And I’ve added the following code (for creating short-code) using my custom functions plugin (e.g. Code Snippets):
function echo_hello_func() {
get_template_part('page-onedemo');
}
add_shortcode('echo-hello', 'echo_hello_func');
This does the job but with a small problem which you can see in the screenshot below:

We need the shortcode content to display exactly where the shortcode is placed. At the moment, we’re seeing it above the existing content. To fix this, we’ll need to use output buffer –
function echo_hello_func() {
ob_start();
get_template_part('page-onedemo');
return ob_get_clean();
}
add_shortcode('echo-hello', 'echo_hello_func');
Doing so helps us to display the shortcode content in the right place –

That’s all in this post. Thanks for reading! 🙂