1. 程式人生 > >2018最新WordPress縮略圖設置方法

2018最新WordPress縮略圖設置方法

ref random 技術 文件夾 display string inf 如果 trim

縮略圖設置的方法很多,但都不全面,且很多教程已經失效了,其中使用插件來實現,可是那些插件都使用過都不能實現效果,所以我整理了一份使用代碼實現縮略圖的方法。

1、找到網站根目錄/wp-content/themes/當前網站主題文件夾/functions.php,使用編輯器在該文件中添加以下代碼:

//設置特色圖片

function wpu_thumbnail() {
global $post;
if ( has_post_thumbnail() ) {
$domsxe = simplexml_load_string(get_the_post_thumbnail());
$thumbnailsrc = $domsxe->attributes()->src;
echo ‘<img width="500" height="309" src="‘.$thumbnailsrc.‘" alt="‘.trim(strip_tags( $post->post_title )).‘" />‘; /*設置圖片大小,我設置寬高比為黃金比例0.618*/


} 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]);
if($n > 0){
echo ‘<img width="500" height="309" src="‘.$strResult[1][0].‘" alt="‘.trim(strip_tags( $post->post_title )).‘" />‘; /*設置圖片大小*/

}else {
$random = mt_rand(1, 5); /*設置隨機圖片的個數,當前圖片個數為5個,註意圖片個數要和這裏相同*/
echo ‘<img width="500" height="309" src="‘.get_bloginfo(‘template_url‘).‘/img/thumb/img‘.$random.‘.png" alt="‘.trim(strip_tags( $post->post_title )).‘" />‘; /*設置圖片大小,設置圖片格式,當前圖片格式為.png*/
}
}
}
/*設置隨機圖片路徑,當前路徑為img,當然也可以設置網絡路徑*/

技術分享圖片

2、在主題文件夾裏新建一個 “img” 文件夾,然後在img文件夾裏再創建一個 “thumb” 文件夾。準備好隨機圖片放進剛建好的 thumb 文件夾裏,需要重點提一下的是圖片的後綴名必須更改為img1.png,img2.png,img3.png,img4.png,img5.png。

3、找到網站根目錄/wp-content/themes/當前網站主題文件夾/index.php,搜索get_template_part( ‘template-parts/content‘, ‘archive‘ );(因主題不同,代碼也會不同,如果搜索不到就搜索 get_template_part),在前面添加 wpu_thumbnail( );

技術分享圖片

4、然後就沒有然後了,大家可以看看我的博客的效果:blog.xinlvtian.com

原文鏈接:https://zhidao.baidu.com/question/1668400791172886707.html,本文根據原文進行了修改

2018最新WordPress縮略圖設置方法