Created
September 17, 2014 05:30
-
-
Save aisin/f01c8761232748c23a38 to your computer and use it in GitHub Desktop.
WordPress 获取文章内容里的首张图片和第一段,如果无图只显示第一段。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_con(){ | |
global $post; | |
$content = get_the_content(); | |
//获取内容的第一段 | |
$str = wpautop( $content ); | |
$str = substr( $str, 0, strpos( $str, '</p>' ) + 4 ); | |
$str = strip_tags($str, '<a><strong><em>'); | |
$res = '<p>' . $str . '</p>'; | |
//获取首张图片 | |
preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $content, $images); | |
if($images[1][0]) { | |
$res = '<p><img src="'. $images[1][0] .'" alt="'. get_the_title() .'"/></p>'.$res; | |
} | |
echo $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment