当前位置: 代码迷 >> Web前端 >> wordpress稿件摘要及缩略图的显示
  详细解决方案

wordpress稿件摘要及缩略图的显示

热度:80   发布时间:2013-08-06 16:47:25.0
wordpress文章摘要及缩略图的显示
先看一下最终实现的网站效果:,如果不是你想要的,下面的内容就可以不看啦。
因为考虑到不是每位博主都对代码很熟,所以写这个方法的时候,我尽量的简化了操作方法,争取大家能看懂并且顺利实现想要的效果。
第一步:将代码粘贴到主题文件functions.php的最下面即可:
//缩略图获取
function dm_the_thumbnail() { 
    global $post; 
    if ( has_post_thumbnail() ) { 
        echo '<a href="'.get_permalink().'" class="pic">';
  $domsxe = simplexml_load_string(get_the_post_thumbnail());
  $thumbnailsrc = $domsxe->attributes()->src; 
  echo '<img src="'.$thumbnailsrc.'" alt="'.trim(strip_tags( $post->post_title )).'" />';
        echo '</a>'; 
    } else {
        $content = $post->post_content; 
        preg_match_all('/<img.*?(?: |\\t|\\r|\\n)?src=[\'"]?(.+?)[\'"]?(?:(?: |\\t|\\r|\\n)+.*?)?>/sim', $content, $strResult, PREG_PATTERN_ORDER); 
        $n = count($strResult[1]);
  $random = mt_rand(1, 20);
        if($n > 0){
            echo '<a href="'.get_permalink().'" class="pic"><img src="'.$strResult[1][0].'" alt="'.get_the_title().'" title="'.get_the_title().'"/></a>'; 
        }else {
            echo '<a href="'.get_permalink().'" class="pic"><img src="'.get_bloginfo('template_url').'/images/random/tb'.$random.'.jpg" alt="'.get_the_title().'" title="'.get_the_title().'"/></a>'; 
        } 
    } 
}
add_theme_support('post-thumbnails');
set_post_thumbnail_size(100, 140, true);

第二步:将如下代码粘贴到主题文件index.php;category.php;archive.php里面的“<div class="intro">”后面即可:
<?php dm_the_thumbnail(); ?>
第三步:将如下css代码添加到主题文件style.css的最下面。
.post .intro img{float: left;width: 140px;height:100px;margin: 12px 10px 8px 15px;_margin: 17px 10px 8px 7px;padding: 4px;border:1px solid #ccc;position:relative;z-index:3;}
OK,完成以上3步后就实现了文章摘要旁边显示缩略图了,默认调用文章内第一张图片,文章内没有的话,就会调用主题包里images文件夹下的random(这个文件夹自己手动建立)里面的例如tb1.jpg,tb2.jpg……tb20.jpg(命名的格式必须照此来),图片大小为100*140,素材自己找吧,嘿嘿~
接下来介绍下自动摘要的方法,其实前面写的文章里面已经介绍过方法,今天只不过是更具针对性了。方法很简单,打开主题文件index.php,然后将如下代码:
<?php if(is_category() || is_archive() || is_home() ) {
the_excerpt();
} else {
the_content('Read the rest of this entry &raquo;');
}
?>
替换为下面的代码即可:
<?php if(is_category() || is_archive() || is_home() ) {
echo '<p>';echo mb_strimwidth(strip_tags(apply_filters('the_excerpt', $post->post_content)), 0, 365,"...");echo '</p><p class="read-more"><a href="'.get_permalink().'" title="'.get_the_title().'" rel="bookmark">阅读全文</a></p>';
}
?>
同样的操作在主题文件category.php和archive.php中进行一下,ok了。
  相关解决方案