wordpress获取文章缩略图功能

十度 wordpress 2015年12月20日 收藏

wordpress在显示文章列表经常需要以图文并茂的形式来展示,这样可以使得整个页面看起来更加的美观,网上有很多类型的wordpress读取缩略图功能的代码,但是都不是非常的完整。

以下获取文章缩略图包含了三个功能:

  • 1、如果文章存在缩略图则直接读取缩略图。
  • 2、如果不存在缩略图则读取文章第一张图片为缩略图。
  • 3、如果文章美图图片则读取指定的默认图片,本文以(/images/thumbnail.jpg)为例。

详细代码如下(将代码拷贝至你主题下的functions.php即可调用使用):

//缩略图获取
function get_the_thumbnail() {
	global $post;
	if (has_post_thumbnail ()) {
		//如果存在缩略图读取之
		echo '<a href="' . get_permalink () . '" class="pic" title="'.trim ( strip_tags ( $post->post_title ) ).'">';
		$domsxe = simplexml_load_string ( get_the_post_thumbnail () );
		$thumbnailsrc = $domsxe->attributes()->src;
		echo '<img src="' . $thumbnailsrc . '" alt="' . trim ( strip_tags ( $post->post_title ) ) . '" />';
		echo '</a>';
	} else {
		//读取文章第一张图片为缩略图
		$content = $post->post_content;
		preg_match_all ( '/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER );
		$n = count ( $strResult [1] );
		if ($n > 0) {
			//文章第一张图片
			echo '<a href="' . get_permalink () . '" class="pic" title="'.trim ( strip_tags ( $post->post_title ) ).'"><img src="' . $strResult [1] [0] . '" /></a>';
		} else {
			//如果文章没有图片则读取默认图片
			echo '<a href="' . get_permalink () . '" class="pic" title="'.trim ( strip_tags ( $post->post_title ) ).'"><img src="' . get_bloginfo ( 'template_url' ) . '/images/thumbnail.jpg" /></a>';
		}
	}
}