Over at RhodiaDrive.com, they wanted to be able to sprinkle featured posts in the sidebar using widgets. Via my solution, the authors can choose a post to feature, add a text widget to the sidebar, and enter a simple shortcode. The widget will then display the post’s title and an excerpt of the content with a link to the post page.
Usage:
[ahs_featuredpost id=364]
Want it? Just copy the code below/after the jump into the functions.php file for your current theme and voila! You can then style the elements in the widget, which are all in a div with class=”featuredpost”.
/*
* shortcode handler to display featured post info in text widget
* author: april hodge silver http://springthistle.com
* @param array attributes from shortcode filter (expects only id)
* @returns string with h3 post title, excerpt in
*/
function ahs_featuredpost_handler($atts) {
extract(shortcode_atts(array(
'id' => null,
), $atts));
if ($id == null) {
echo '
This shortcode requires a post ID!
';
} else {
global $post;
$out = '';
$myposts = get_posts('numberposts=1&include='.$id);
foreach($myposts as $post){
setup_postdata($post);
$ignore[] = $post->ID;
$out .= '
';
$out .= '
'.$post->post_title.'
';
$out .= '
'.substrws(strip_tags($post->post_content),240).'... Read on »
';
$out .= "
";
}
return $out;
}
}
// register the above function to be connected to a new shortcode [ahs_featuredpost]
add_shortcode('ahs_featuredpost', 'ahs_featuredpost_handler');
// so that widget text is analyzed for shortcodes
add_filter('widget_text', 'do_shortcode');
You can get the substrws() function from php.net