Posted By

jschultz76 on 04/18/12


Tagged

php wordpress excerpt


Versions (?)

WordPress Recent News/Posts with or without Featured Image


 / Published in: PHP
 

This will show a number of recent posts along with their associated featured image (thumbnail) if they have one. The template code asks for the 2 most recent posts with the custom post type of "news." Change the quantity and post type as needed. This also uses a custom excerpt generator, which isn't necessary except that this particular code references it.

  1. <?php
  2.  
  3. // custom excerpt generator. put into functions.php.
  4. function flexcerpt($excerpt = '', $excerpt_length = 50, $readmore = "Read more&raquo;", $tags = '<a>', $permalink = null) {
  5. global $post;
  6. $excerpt = strip_tags($excerpt, $tags);
  7. $excerpt = strip_shortcodes($excerpt);
  8. $string_check = explode(' ', $excerpt);
  9. if ($permalink === null) {
  10. $permalink = get_permalink();
  11. }
  12.  
  13. if (count($string_check, COUNT_RECURSIVE) > $excerpt_length) {
  14. $new_excerpt_words = explode(' ', $excerpt, $excerpt_length+1);
  15. array_pop($new_excerpt_words);
  16. $excerpt_text = implode(' ', $new_excerpt_words);
  17. $temp_content = strip_tags($excerpt_text, $tags);
  18. $excerpt = preg_replace('|\[(.+?)\](.+?\[/\\1\])?|s','',$temp_content);
  19. // $excerpt .= ' ... <a href="' . $permalink . '">' . $readmore . '</a>';
  20. // return $excerpt;
  21. } else {
  22. //return $excerpt;
  23. }
  24.  
  25. $excerpt .= '... <a href="' . $permalink . '">' . $readmore . '</a>';
  26. return $excerpt;
  27. }
  28.  
  29. ?>
  30.  
  31.  
  32. <!-- this goes into the template file. it is using a custom post type called "news" and can be changed to whatever is needed. -->
  33. <?php $news = get_posts( array( 'numberposts' => 2, 'post_type' => 'news' ) ); ?>
  34. <?php foreach ( $news as $post ): ?>
  35. <?php setup_postdata($post); ?>
  36. <div class="home-news-article <?php echo (has_post_thumbnail() ? 'with-thumbnail' : 'no-thumbnail') ?>">
  37. <?php if (has_post_thumbnail()): ?>
  38. <div class="home-news-thumbnail">
  39. <?php the_post_thumbnail( 'news-thumbnail' ); ?>
  40. </div><!--.home-news-thumbnail-->
  41. <?php endif ?>
  42. <div class="home-news-content">
  43. <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
  44. <?php if (!empty($post->post_excerpt)): ?>
  45. <?php echo flexcerpt( $post->post_excerpt ); ?>
  46. <?php else: ?>
  47. <?php echo flexcerpt( get_the_content() ); ?>
  48. <?php endif ?>
  49.  
  50. </div><!--.home-news-content-->
  51. </div><!--.home-news-article-->
  52. <?php endforeach; ?>

Report this snippet  

You need to login to post a comment.