In this code snippet we are exploring how we can create a shortcode to display custom post type. With this code snippet we are utilising WordPress shortcode API.
What is WordPress Shortcode API
The API enables plugin developers to create special kinds of content (e.g. forms, content generators) that users can attach to certain pages by adding the corresponding shortcode into the page text.
The API handles all the tricky parsing, eliminating the need for writing a custom regular expression for each shortcode. Helper functions are included for setting and fetching default attributes. The API supports both self-closing and enclosing shortcodes.
What is WordPress Post type
WordPress can hold and display many different types of content. A single item of such a content is generally called a post, although post is also a specific post type. Internally, all the post types are stored in the same place, in the wp_posts database table, but are differentiated by a column called post_type.
Shortcode creation code to display custom post type
<?php function abScrollingTestimonials() { ob_start(); $data = '<div class="testiScroller">'; $query = new WP_Query('post_type=testimonial&showposts=5&orderby=rand'); while( $query->have_posts() ):$query->the_post(); $data .= '<div class="singleTestimonial" id="testomial-'.get_the_ID().'">'; $data .= ab_improved_excerpt_nop(); $data .= '<div class="clientDetails">- '.get_the_title().'<span>('.get_the_excerpt().')</span></div>'; $data .= '</div>'; endwhile; wp_reset_postdata(); $data .= '</div>'; return $data; } add_shortcode('fadingTestimonials','abScrollingTestimonials'); ?>