一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

wordpress调用文章内容中头一张图片

时间:2014-04-23 编辑:简简单单 来源:一聚教程网

本节,高时银博客就跟大家分享一下“怎样调用文章中的第一张图片”。

方法很简单,在主题模板函数文件function.php中添加下面这段代码:

 代码如下 复制代码

//获取文章首张图片
function catch_that_image() {
global $post, $posts;
$first_img = ”;
ob_start();
ob_end_clean();
$output = preg_match_all(‘//i’, $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = “/images/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('//i', $post->post_content, $matches);
    $first_img = $matches [1] [0];
    if(empty($first_img)){ // 既www.111com.net没有缩略图,文中也没有图,设置一幅默认的图片
      $first_img = "/images/default.jpg";
    }
  }
  return $first_img;
}

2. 在页面需要的地方增加如下标签代码

这个函数的作用是获取到文章中的第一张图片的地址,然后,再将这个地址传递到上一节中的图片地址中,就实现了缩略图片的调用。

自动读取文章中的第一张插图为缩略图

如果连文章中也没有插图,那么就读取设置好的默认图片。

 代码如下 复制代码
//thumbnails
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 200, 140 ,true );
function don_the_thumbnail() {
global $post;
// 判断该文章是否设置的缩略图,如果有则直接显示
if ( has_post_thumbnail() ) {
echo '';
the_post_thumbnail();
echo '
';
} else { //如果文章没有设置缩略图,则查找文章内是否包含图片
$content = $post->post_content;
preg_match_all('//sim', $content, $strResult, PREG_PATTERN_ORDER);
$n = count($strResult[1]);
if($n > 0){ // 如果文章内包含有图片,就用第一张图片做为缩略图
echo '';
}else { // 如果文章内没有图片,则用默认的图片。
echo '';
}
}
}

上一节的缩略图调用,我们还可以做成侧边栏的图片展示和相关文章的图片展示,这个,你都可以根据自己的需要来设计。呵呵,今天就分享到这里了。

热门栏目