Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andandehei/8928266 to your computer and use it in GitHub Desktop.
Save andandehei/8928266 to your computer and use it in GitHub Desktop.
获取文章中第一张图片并显示图片 代码预留
①将以下代码粘贴到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