简体   繁体   中英

Show x recent posts on Wordpress with title, date and excerpt

I'm looking to find a way to show the last 5 posts on the homepage of my Wordpress website, so i assume i will need to utilise shortcodes to do this, however i cannot find any pre-existing code to add to functions.php that will show the title, date and post excerpt.

Could someone possibly help me with this?

There are a variety of ways to do this, but the basic idea is similar to the code you'll see in your theme's INDEX.PHP page. You do a query, loop through to show the posts, then reset the query at the end so what you did doesn't interfere with your main page.

function Last5posts()
{
    $args = array( "showposts" => 5 );                  
    query_posts($args);

    $content = "";

    if( have_posts() ) : 

        while( have_posts() ) :

            the_post();
            $link = get_permalink();
            $title = get_the_title();
            $date = get_the_date();                              

            $content .= "<div style='padding: 5px; border: 1px solid red'>";
            $content .= "<h3><a href='$link' target='_top'>$title / $date</a></h3>\n";
            $content .= "<p class='excerpt'>" . get_the_excerpt() . "</p>";
            $content .= "</div>";

        endwhile;

        wp_reset_query();

    endif;

    // Leave one line commented out depending on usage
    echo $content;   // For use as widget
    //return $content; // for use as shortcode
}

To register this as a widget, enable the "echo" at the end, then add this line to the bottom of your file:

register_sidebar_widget(__('Last 5 Posts'), 'Last5posts');

You may want to add some extra code to place the output into a widget wrapper DIV like your other sidebar widgets. (Or, not if you use it somewhere besides a traditional sidebar.)

You could also register this as a shortcode handler using the line below. Comment out the "echo" at the end and uncomment the "return".

add_shortcode('Last5Posts', 'Last5posts' );         

You'll want to make sure that you don't use the shortcode in blog posts or you might end up calling this recursively. Probably a bad thing.

You'll probably also want to add a theme-specific prefix to the function name to avoid namespace collisions.

<?php 

    $args = array('numberposts' => 5);

    $recent_posts = wp_get_recent_posts($args);

    foreach( $recent_posts as $recent ){
      echo $recent["post_title"].' '.$recent['post_date'].' '.$recent['post_excerpt'].'<br />';
    }
?>

The Wordpress Codex isn't that bad.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM