This tutorial goes a bit indepth with WordPress shortcodes, in this case, displaying multiple post types for your page or post. This shortcode is based on the code submitted by Pippin Williamson of Pro Blog Design in the article entitled “Working with WordPress Shortcodes”. Pippin shows some impressive expansion on the WordPress Shortcodes functionality, including the shortcode to display a single Custom Post Type.
I am basically tweaking the code he showed for no. 8 slightly, in effect, allowing the user to enter MULTIPLE post types. Below is the code he gave:
function news_shortcode()
{
//The Query
query_posts('post_type=news');
//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo '<h3><a href="'; echo the_permalink(); echo '">'; echo the_title(); echo '</a></h3>';
echo the_excerpt();
endwhile; else:
endif;
//Reset Query
wp_reset_query();
}
add_shortcode('news', 'news_shortcode');
This allows you to use [news] to activate the code above and display the ‘news’ custom post type. Works well but what if you wanted to display more? Instead of going back and changing the code, why not use a variable that can be changed in the post editor box and not have to return to the original code?
The alternative below will allow you to activate and display multiple post types:
function customPostType_shortcode()
{
extract(shortcode_atts(array(
'type' => 'post',
'limit' => '10',
),$atts));
//The Query
query_posts('post_type='.$type.'&showposts='.$limit);
//The Loop
if ( have_posts() ) : while ( have_posts() ) : the_post();
echo "<h3><a href=\"".the_permalink($post->ID)."\">".get_the_title($post->post_title)."</a></h3>";
echo the_excerpt();
endwhile; else:
endif;
//Reset Query
wp_reset_query();
}
add_shortcode('customPost', 'customPostType_shortcode');
The above code creates a [customPost] shortcode with a $type and a $limit variable, allowing us to specify the post type(or types) with a shortcode like this:
[customPost type=movies,books limit=5]
This will draw 5 recent posts from the movies and books custom post types. If no value is given then the default post type will be post and 10 will be listed instead.
And that’s pretty much it!!!
What else could be added to this? Let me know in the comments below.
September 30th, 2010 at 8:41 pm
Excellent modification of my shortcode. This is much better!
September 30th, 2010 at 10:00 pm
Thanks Pippin
October 26th, 2010 at 9:37 am
Good day!This was a really terrific Topics!
I come from roma, I was fortunate to come cross your blog in google
Also I obtain much in your website really thank your very much i will come again
April 28th, 2011 at 5:17 pm
Awesome work
one thing you could add would be paging options.
May 2nd, 2011 at 10:39 pm
A BIG THANK YOU on how to use shortcodes with Custom Post Types! Now only to get my custom taxonomies to work!