Use a very basic shortcode to call a Custom Post Type

Today’s tutorial is all about the WordPress shortcode function. It will be very basic but will give you a clear understanding how to create the shortcode function.

I personally just love using shortcodes and it is so easy to build. In this tutorial, I want to show you how to display a WordPress loop of a Custom Post Type on any page.

For example, let say the Custom Post Type consists of a Title, Editor, and an Excerpt. We want to display all the posts with a shortcode. Please note that I will not show you how to create a Custom Post Type in this tutorial. I will create a separate tutorial on that.

Ps. All custom code must be placed inside the child theme function.php file.

First, let us create the shortcode function. We will call it “cpt_loop_shortcode”.  We also create a name for the shortcode, “ctploop”.  So now when we use “[ctploop]” the function will display on that page.

[snippet slug=ctp-shortcode lang=php]

The next step we are going to do is call the WordPress loop and display the title and content. I want to bring in a little twist 🙂 We are only going to display this content for Logged in users. For that, we use this simple if statement that starts with “if(is_user_logged_in()) {} “.

For the WordPress loop code, you can read more on this page. For our loop, we going to add some parameters to tell the loop to look for the Custom Post Type and how many posts to show. We are going to display the title and excerpt. But you can use some of the following to build your “shortcode loop”.

  • get_the_title()
  • get_the_excerpt()
  • get_the_content()
  • get_the_date() 
  • get_the_time()

We are also going to place it in the shortcode function. Remember that this will only to show to login users, I only used it in the example to show you little more functionality. Remember you will also need to style it to make it pretty for your users.

Here is the full code for a very basic Custom Post Type ShortCode loop 🙂 You can call it with  “[ctploop]”  on any page you want.

[snippet slug=cptloop lang=php]

Need any help? If you are a iAdminWP customer you can create a ticket and we will help you set up a shortcode like this. Not yet a customer? Please give us a try: click here

Post a comment