Advertisement
urosevic

WordPress: Get recent posts with thumbnail

Feb 1st, 2016
153
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $excerpt_length = 15; // words
  2. $thumbnail_size = 'thumbnail';
  3. $number_of_posts = 5;
  4.  
  5. $args = array(
  6.     'numberposts' => $number_of_posts, // number of posts
  7.     'post_status' => 'publish'
  8. );
  9. $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
  10.  
  11. foreach( $recent_posts as $recent ) {
  12.  
  13.     $permalink = get_permalink( $recent['ID'] );
  14.     $post_title = esc_attr( $recent['post_title'] );
  15.     if ( empty( $recent['post_excerpt'] ) ) {
  16.         $the_excerpt = strip_tags( strip_shortcodes( $recent['post_content'] ) );
  17.         $words = explode( ' ', $the_excerpt, $excerpt_length + 1 );
  18.         if ( count( $words ) > $excerpt_length ) {
  19.             array_pop( $words );
  20.             array_push( $words, '…' );
  21.             $the_excerpt = implode( ' ', $words );
  22.         }
  23.     } else {
  24.         $the_excerpt = $recent['post_excerpt'];
  25.     }
  26.  
  27.     // Open block
  28.     echo '<div class="item clearfix">';
  29.  
  30.     // Thumbnail
  31.     if ( has_post_thumbnail( $recent['ID'] ) ) {
  32.         printf(
  33.             '<a href="%1$s" title="%2$s">%3$s</a>',
  34.             $permalink,
  35.             $post_title,
  36.             get_the_post_thumbnail( $recent['ID'], $excerpt_length )
  37.         );
  38.     }
  39.  
  40.     // Title
  41.     printf(
  42.         '<p class="post-title"><a href="%1$s" rel="bookmark" title="Permanent Link to %2$s">%2$s</a></p>',
  43.         $permalink,
  44.         $post_title
  45.     );
  46.  
  47.     // Excerpt
  48.     printf(
  49.         '<p class="post-summary">%1$s</p>',
  50.         $the_excerpt
  51.     );
  52.  
  53.     // Close block
  54.     echo '</div>';
  55.  
  56. } // END foreach
Advertisement
RAW Paste Data Copied
Advertisement