Learn in this tutorial how to display entries from a WordPress CPT in grid layout using a shortcode without the need for plugins.
One of the most recurring requests from OsomCode subscribers is how to display a loop of entries from a Custom Post Type anywhere on the web.
And if it can be in grid format even better.
So in today’s tutorial you’ll see how to get it.
This would be the final result:
Are you interested? Read on. 😉
Steps to display a CPT entries loop via WordPress shortcode
1. Generate the shortcode to display the CPT inputs
Add the following code at the end of functions.php or in your functionality plugin:
To see this and another 1097 code snippets of this website, login or subscribe here.
With this code you create a loop that will displya the course CPT entries.
The elements you show are (in order):
- Featured image (linked to the entry)
- Title (linked to entry)
- Excerpt
And you can modify:
- The CTP (in this case “course”)
- The criteria for ordering (in this case by date)
- Descending order (in this case DESC, but you can change to ASC)
- Number of entries shown (in this case 6).
In addition, you encapsulate it within a shortcode with add_shortcode so that they are shown wherever you want just by putting [courses].
You almost have it.
2. Give grid design to the input loop
Add the following fragment at the end of the style.css file:
To see this and another 1097 code snippets of this website, login or subscribe here.
This allows you to display the entries in a grid format. You can play with the minmax value (250px) to change the number of columns displayed.
You only have one step left.
3. Enter the shortcode where you want
The advantage of the shortcodes is that you can insert them anywhere on the web.
You will only have to write “[your_shortcode]” where you want it to be displayed, in this case [courses].
Important:
- If you are using the classic editor, use the HTML tab to introduce the shortcode.
- In case you are already using the block editor you can add it to the normal paragraph block, the HTML block or the shortcode block. All of them will render the content correctly.
Conclusions
If you want to display a loop of entries from a CPT in grid layout without having to add them by hand or use a plugin, now you know how to do it using a shortcode.
Any questions? Let me know in the comments.
And if you want to give me any suggestion for future tutorials, leave it in the contact form. Advantages of being a subscriber. 😉