close

在很多模板製作中,朋友們希望獲取文章的第一張圖作為文章列表中文章標題前的圖片展示,今天寫一個函數,用來實現這一效果。通過本函數,你可以在今後的模板設計中,不再考慮什麼情況下使用圖片,應該如何調用文章圖片等問題,只需在恰當的位置調用本函數即可。

function get_post_first_pic($post_id,$default=0,$link=0,$style=''){
$post=get_post($post_id);
$thumb=get_the_post_thumbnail($post_id,array('alt'=>trim(strip_tags($post->post_title)),'title'=>trim(strip_tags($post->post_title))));
if(!$thumb){
preg_match('/<img.+src=[\'"]([^\'"]+)[\'"].* \/>/i',$post->post_content, $index_piclink);
if($index_piclink[1]){
$thumb='<img src="'.$index_piclink[1].'" title="'.$post->post_title.'" alt="'.$post->post_title.'" '.$style.' />';
}else{
if($default!=0)$thumb='<img src="'.get_bloginfo('template_url').'/images/default.jpg" title="'.$post->post_title.'" alt="'.$post->post_title.'" '.$style.' />';
}
}
if($thumb&&$link!=0&&$link!='')$output='<a href="'.get_permalink().'" title="'.$post->post_title.'">'.$thumb.'</a>';
else $output=$thumb;
return $output;
}
function post_first_pic($post_id,$default=0,$link=0,$style=''){
echo get_post_first_pic($post_id,$default,$link,$style);
}

詳解
第一個函數是獲取函數,第二個函數則將第一個函數中獲取的結果顯示出來。

get_post_first_pic($post_id,$default=0,$link=0,$style='')有四個參數,其中$post_id指要獲取的文章ID,如果再LOOP循環中,可以直接用$post->ID代替,顯示該文章的第一張圖片;$default用於在該文章沒有圖片的情況下,是否顯示模板目錄下的/images/default.jpg作為替代圖片,非0則使用;$link則表示是否將該圖片鏈接指向文章,如果為0,則不帶鏈接;$style就是對圖片添加新的屬性,如你可以將$style='style="border:none;"';從而添加特定的附屬屬性

當文章中沒有圖片,$default=0時,則不顯示任何內容。
例子
下面是一個調用的例子:

<?php if(function_exists('post_first_pic'))post_first_pic($post->ID,1,1,'style="width:150px;height:150px;"');?>
<?php the_excerpt(); ?>

那關於如果不想在首頁上出現太多文字,只想讓圖片做為流覽圖--那

<?php the_excerpt(); ?>這個可以用Read More代替

修改位置通常為index.php或是content.php

arrow
arrow
    全站熱搜

    t909092 發表在 痞客邦 留言(0) 人氣()