WordPress – Recent Posts Shortcode

Show recent posts on a page using a shortcode.

I keeping finding useful tasks for WordPress Shortcodes – they must be one of the best WordPress features. In this case the client wanted to show Posts as news items on the home page and a shortcode was the obvious way to do this.

 

// Enable [recent-posts] shortcode
// http://wp.smashingmagazine.com/2012/05/01/wordpress-shortcodes-complete-guide/
// http://codex.wordpress.org/Function_Reference/the_content

function recent_posts_function()
{
    $return_string = ”;
    $second_query = new WP_Query(‘showposts=5’);
    if ($second_query->have_posts()) :
    while ($second_query->have_posts()) : $second_query->the_post();
    $content = get_the_content();
    $content = apply_filters(‘the_content’, $content);
    $content = str_replace(‘]]>’, ‘]]>’, $content);
    $return_string = $return_string.'<h2>’.get_the_title().'</h2>’.$content;
    endwhile;
    endif;
    wp_reset_postdata();
    return $return_string;
}

function register_shortcodes()
{
    add_shortcode(‘recent-posts’, ‘recent_posts_function’);
}

add_action(‘init’, ‘register_shortcodes’);

 

105 views

Need help? Let me take care of your IT issues.

Share this page

Scroll to Top