custompostshortcode

Execute Multiple Custom Post Type Queries using WordPress Shortcodes

Posted in Web Design/Development, Wordpress | 5 Comments

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.



5 Comments to “Execute Multiple Custom Post Type Queries using WordPress Shortcodes”






Recommended

Expert Help with WordPress
Learn how you can market your business on Twitter
Get the Book now! Use 25% discount code 'november25'
Hostgator - Cheap and Reliable Web Hosting - WordPress friendly

Incoming Tweets