Learn in this tutorial how to display WordPress CPT posts in grid format with an overlay (title overlaying the image) using a shortcode without plugins.
One of the most recurring requests from OsomCode subscribers is how to display a loop of Custom Post Type posts on any website.
And if it can be in grid format even better. 😉
So in today’s tutorial you are going to see how to achieve it.
This would be the final result:
Interested? Read on. 😉
Steps to display a loop of CPT posts with overlay using a shortcode in WordPress
Add the following code at the end of functions.php or in your functionality plugin:
1. Generate the shortcode to display the CPT entries
With this code you create a loop that displays the featured image of the CPT course entries with the title over it.
And you can modify:
- The CTP (in this case “course”)
- The sorting criteria (in this case by title)
- Descending order (in this case ASC, but you can change it to DESC)
- Number of posts to display (in this case 6)
Also, you encapsulate it inside a shortcode with
add_shortcode so you insert them wherever you want by just putting [posts_overlay].
In this case, the image size you use is
gb-block-post-grid-landscape, but if you don’t have Genesis Blocks installed you can use the native WordPress ones or the ones created by other plugins (or theme). If you want to know all the image sizes you have in your WordPress installation take a look at this tutorial.
You’re almost there.
2. Apply grid layout to the posts loop and create the overlay effect
Add the following snippet to the end of the style.css file:
With this you get to display the entries in grid format. You can play with the minmax value (300px) to change the number of columns displayed.
Depending on the length of the title you will have to adjust the size of the title (in this case 32px) and the position relative to the top (40% in this example).
You can also adjust the color or opacity of the overlay to your liking.
If for example you want the overlay to only show when hovering over the entry (as shown in the GIF above), you can replace the CSS above with this one:
There is only one step left.
3. Insert the shortcode where you want
The advantage of shortcodes is that you can insert them anywhere on the website.
Just type “[your_shortcode]” where you want it to be displayed, in this case [posts_overlay].
- If you are using the classic editor, use the HTML tab to insert the shortcode.
- In case you are already using the new block editor (Gutenberg) you can add it to the normal paragraph block, the HTML block or the shortcode block. All of them will render the content correctly.
If you want to display a loop of CPT entries in a grid format and with the title superimposed over the featured image, now you know how to do it with 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. 😉