Last active
August 29, 2015 13:56
-
-
Save andandehei/8928266 to your computer and use it in GitHub Desktop.
获取文章中第一张图片并显示图片 代码预留
This file contains hidden or 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
①将以下代码粘贴到functions.php文件中。 | |
function catch_that_image() { | |
global $post, $posts; | |
$first_img = ''; | |
ob_start(); | |
ob_end_clean(); | |
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); | |
//获取文章中第一张图片的路径并输出 | |
$first_img = $matches [1] [0]; | |
//如果文章无图片,获取自定义图片 | |
if(empty($first_img)){ //Defines a default image | |
$first_img = "/images/default.jpg"; | |
//请自行设置一张default.jpg图片 | |
} | |
return $first_img; | |
} | |
②在需要显示图片的地方输出图片: | |
<?php echo catch_that_image() ?> | |
方法2.如果我们手动设置了特色图像,而且文章中又有图片,那该如何显示呢?我们自此可以使用逻辑判断,给他们一个优先条件。此方法网上代码重复太多,已经不知道原创是谁了... | |
function catch_that_image( $id ) { | |
// global $post, $posts; | |
$first_img = ''; | |
// 如果设置了缩略图 | |
$post_thumbnail_id = get_post_thumbnail_id( $id ); | |
if ( $post_thumbnail_id ) { | |
$output = wp_get_attachment_image_src( $post_thumbnail_id, 'large' ); | |
$first_img = $output[0]; | |
} | |
else { // 没有缩略图,查找文章中的第一幅图片 | |
ob_start(); | |
ob_end_clean(); | |
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); | |
$first_img = $matches [1] [0]; | |
if(empty($first_img)){ // 既没有缩略图,文中也没有图,设置一幅默认的图片 | |
$first_img = "/images/default.jpg"; | |
} | |
} | |
return $first_img; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment