urosevic icon

WordPress: Get recent posts with thumbnail

urosevic | PRO | 02/01/16 11:33:07 AM UTC | 0 ⭐ | 514 👁️ | Never ⏰ | []
PHP |

1.33 KB

|

None

|

0 👍

/

0 👎

$excerpt_length = 15; // words
$thumbnail_size = 'thumbnail';
$number_of_posts = 5;
 
$args = array(
    'numberposts' => $number_of_posts, // number of posts
    'post_status' => 'publish'
);
$recent_posts = wp_get_recent_posts( $args, ARRAY_A );
 
foreach( $recent_posts as $recent ) {
 
    $permalink = get_permalink( $recent['ID'] );
    $post_title = esc_attr( $recent['post_title'] );
    if ( empty( $recent['post_excerpt'] ) ) {
        $the_excerpt = strip_tags( strip_shortcodes( $recent['post_content'] ) );
        $words = explode( ' ', $the_excerpt, $excerpt_length + 1 );
        if ( count( $words ) > $excerpt_length ) {
            array_pop( $words );
            array_push( $words, '…' );
            $the_excerpt = implode( ' ', $words );
        }
    } else {
        $the_excerpt = $recent['post_excerpt'];
    }
 
    // Open block
    echo '<div class="item clearfix">';
 
    // Thumbnail
    if ( has_post_thumbnail( $recent['ID'] ) ) {
        printf(
            '<a href="%1$s" title="%2$s">%3$s</a>', 
            $permalink, 
            $post_title,
            get_the_post_thumbnail( $recent['ID'], $excerpt_length ) 
        );
    }
 
    // Title
    printf(
        '<p class="post-title"><a href="%1$s" rel="bookmark" title="Permanent Link to %2$s">%2$s</a></p>',
        $permalink,
        $post_title
    );
 
    // Excerpt
    printf(
        '<p class="post-summary">%1$s</p>',
        $the_excerpt
    );
 
    // Close block
    echo '</div>';
 
} // END foreach

Comments