In this article, I am sharing a code snippet to create a shortcode for custom post type. By using this code snippet, you will be able to create a shortcode and display your custom posts in the frontend of your website.
But before moving further, I am assuming you already have a custom post type registered in your wordpress website.
Shortcode for Custom Post Type
In this code snippet, let say I have a custom post type named movies and I want to create a shortcode for this to display posts.
Add the code given below to your theme’s functions.php or in your plugin’s specific file. This will create a shortcode [movie-list] in your theme.
// Create Shortcode to Display Movies Post Types function diwp_create_shortcode_movies_post_type(){ $args = array( 'post_type' => 'movies', // don't forget to replace it with your custom post type name 'posts_per_page' => '10', 'publish_status' => 'published', ); $query = new WP_Query($args); if($query->have_posts()) : while($query->have_posts()) : $query->the_post() ; $result .= '<div class="movie-item">'; $result .= '<div class="movie-poster">' . get_the_post_thumbnail() . '</div>'; $result .= '<div class="movie-name">' . get_the_title() . '</div>'; $result .= '<div class="movie-desc">' . get_the_content() . '</div>'; $result .= '</div>'; endwhile; wp_reset_postdata(); endif; return $result; } add_shortcode( 'movies-list', 'diwp_create_shortcode_movies_post_type' ); // shortcode code ends here
Now you can use this shortcode [movie-list] to display the 10 recent movie info as a list in your website.
Note: In the above code, for designing purpose and make things better aligned, I have used some CSS classes. You can find those CSS classes below. However, you can create your own CSS classes as well to make it fit as per your designs.
.movie-item{ width: 100%; margin:0 auto; clear: both; margin-bottom: 20px; overflow: auto; border-bottom: #eee thin solid; padding-bottom: 20px; } .movie-poster{ width: 160px; float: left; margin-right: 25px; } .movie-poster img{ width: 100%; height: auto; } .movie-name{ font-size: 35px; }
If you want to create shortcode to display custom posts from specific or multiple categories, then I have a written a detailed article about shortcodes to display posts from categories. Please check that out!.