因为专注
所以专业

wordpress怎么调用内容文章缩略图片

1. 首先在 function.php 中新增函数 catch_that_image


参考函数一:

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 = "http://yourwebsite/default.jpg";
  }
  return $first_img;
}



参考函数二:
function catch_the_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 = "http://yourdomain.tld/images/default.jpg";
    }
  }
  return $first_img;
}


2. 在页面需要的地方增加如下标签代码:
<img src="<?php echo catch_that_image() ?>" alt="" />
 


未经允许不得转载:肖兴来SEO博客 » wordpress怎么调用内容文章缩略图片
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址