WP: Shortcode To Display Page Template

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! 🙂

WP: Create A Shortcode

Do you know about shortcodes in WordPress? It’s basically some text that you can add between square brackets and it turns into some feature on the front-end.

In this post, let’s look at how to create a shortcode in WordPress. It’s quite simple and the example below explains how we can create a simple shortcode called echo-hello

function echo_hello_func() {
 	return 'Hello Hello Hello';   
}
 
add_shortcode('echo-hello', 'echo_hello_func');

This code can be added to your theme’s functions.php file or via a third party plugin like code-snippets.

Once done, you will be able to add [echo-hello] shortcode in your posts/pages which will basically print Hello Hello Hello on the front-end.

We can of course do more complex stuff with it but I hope this gives you a basic idea on how to create a shortcode on a WordPress site.