This is a one-off, but it’s interesting to me so I’m sharing. I have a site with very pretty archives. It came with a video Custom Post-Type, but no archives for that type. Now I could have edited the theme, or overwritten the CPT, but I decided instead to embrace what I had and add on. What if I made a shortcode for [recent-videos] that showed me the recent videos?
This code was specifically designed for the custom post-type ‘Videos’ in the News Theme by Theme Hybrid.
add_shortcode('recent-videos', 'recent_videos_shortcode');
function recent_videos_shortcode($atts) {
extract( shortcode_atts( array(
'posts_per_page' => '10',
), $atts ) );
$args = array(
'post_type' => 'video',
'posts_per_page' => $posts_per_page,
);
$vidlist = new WP_Query($args);
if ( $vidlist->have_posts() ):
$return .= '<div class="display-vidlist archive" style="margin: 0 0 0 -20px!important;">';
while ( $vidlist->have_posts() ): $vidlist->the_post(); global $post;
$image = '<a class="image" href="'. get_permalink() .'">'. get_the_post_thumbnail($post->ID, thumbnail, array('class' => 'news-thumbnail')).'</a> ';
$title = '<h2 class="entry-title"><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></h2>';
$date = '<div class="byline"><abbr class="published" title="'. get_the_date('l, F jS, Y, g:i a') .'">'. get_the_date('F j, Y') .'</abbr></span></div>';
$excerpt = '<div class="entry-summary"><p>' . get_the_excerpt() . '</p></div>';
$output = '<div id="post-'. get_the_ID() .'" class="hentry videos publish author-'. get_the_author_meta( 'user_login' ) .' has-excerpt">' . $image . $title . $date . $excerpt . '</div>';
$return .= apply_filters( 'display_posts_shortcode_output', $output, $atts );
endwhile;
$return .= '</div>';
endif; wp_reset_query();
if (!empty($return)) return $return;
}
The heavy lifting was formatting it to look right, and I’m not happy about my hack in class="display-vidlist archive" style="margin: 0 0 0 -20px!important;" but I also wasn’t 100% sure I wanted to separate the css just yet.
Most people will need to change 'post_type' => 'video', to their CPT, and remove the style hack.
I can already see where I’d extend this if I wanted to allow more arguments. The only one I put in was for the number of posts: [recent-videos posts_per_page=10] — You could easily add in one to allow ANY post type:
function recent_videos_shortcode($atts) {
extract( shortcode_atts( array(
'posts_per_page' => '10',
'post_type' => 'post',
), $atts ) );
$args = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
);
Then call [recent-videos post_type="video"] — Of course, if you do that, you should probably fork this into ‘Recent Posts Shortcode’ and rebrand recent-video to something else.
Which you totally can do (this, as with all my code, is licensed GPL2).
