Return to Snippet

Revision: 56843
at April 18, 2012 23:44 by jschultz76


Initial Code
<?php

// custom excerpt generator. put into functions.php.
function flexcerpt($excerpt = '', $excerpt_length = 50, $readmore = "Read more&raquo;", $tags = '<a>', $permalink = null) {
	global $post;
	$excerpt = strip_tags($excerpt, $tags);
	$excerpt = strip_shortcodes($excerpt);
	$string_check = explode(' ', $excerpt);
	if ($permalink === null) {
		$permalink = get_permalink();
	}

	if (count($string_check, COUNT_RECURSIVE) > $excerpt_length) {
		$new_excerpt_words = explode(' ', $excerpt, $excerpt_length+1);
		array_pop($new_excerpt_words);
		$excerpt_text = implode(' ', $new_excerpt_words);
		$temp_content = strip_tags($excerpt_text, $tags);
		$excerpt = preg_replace('|\[(.+?)\](.+?\[/\\1\])?|s','',$temp_content);
		// $excerpt .= ' ... <a href="' . $permalink . '">' . $readmore . '</a>';
		// return $excerpt;
	} else {
		//return $excerpt;
	}
	
	$excerpt .= '... <a href="' . $permalink . '">' . $readmore . '</a>';
	return $excerpt;
}

?>


<!-- this goes into the template file. it is using a custom post type called "news" and can be changed to whatever is needed. -->
<?php $news = get_posts( array( 'numberposts' => 2, 'post_type' => 'news' ) ); ?>
<?php foreach ( $news as $post ): ?>
	<?php setup_postdata($post); ?>
	<div class="home-news-article <?php echo (has_post_thumbnail() ? 'with-thumbnail' : 'no-thumbnail') ?>">
		<?php if (has_post_thumbnail()): ?>
			<div class="home-news-thumbnail">
				<?php the_post_thumbnail( 'news-thumbnail' ); ?>
			</div><!--.home-news-thumbnail-->
		<?php endif ?>
		<div class="home-news-content">
			<h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>
			<?php if (!empty($post->post_excerpt)): ?>
				<?php echo flexcerpt( $post->post_excerpt ); ?>
			<?php else: ?>
				<?php echo flexcerpt( get_the_content() ); ?>
			<?php endif ?>
			
		</div><!--.home-news-content-->
	</div><!--.home-news-article-->
<?php endforeach; ?>

Initial URL


Initial Description
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.

Initial Title
WordPress Recent News/Posts with or without Featured Image

Initial Tags
php, wordpress

Initial Language
PHP