WordPress 抓取文章第一張圖片顯示在首頁

WordPress 某些主題在首頁只會顯示"特色圖片",你可以用以下兩種方式直接顯示文章的第一張照片

方式1
//抓取文章第一張圖片
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 = "/images/default.jpg";
}
return $first_img;
}

<p><img src="<?php echo catch_that_image() ?>"></p><!-- 顯示第一張圖片 -->

方式2:
複製下面的代碼到 functions.php 中

//Automatically Set the Featured Image in WordPress
function autoset_featured() {
global $post;
$already_has_thumb = has_post_thumbnail($post->ID);
if (!$already_has_thumb)  {
$attached_image = get_children( "post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=1" );
if ($attached_image) {
foreach ($attached_image as $attachment_id => $attachment) {
set_post_thumbnail($post->ID, $attachment_id);
}
}
}
}  //end function
add_action('the_post', 'autoset_featured');
add_action('save_post', 'autoset_featured');
add_action('draft_to_publish', 'autoset_featured');
add_action('new_to_publish', 'autoset_featured');
add_action('pending_to_publish', 'autoset_featured');
add_action('future_to_publish', 'autoset_featured');

Wordpress 抓取文章第一張圖片顯示在首頁
Wordpress 抓取文章第一張圖片顯示在首頁
關於作者 多力哥
Wordpress 抓取文章第一張圖片顯示在首頁
影像創作攝影師/網頁動畫設計師/系統網路工程師/水草研究生
景文科大畢業後,我成為一名網站動畫設計師,並副修MIS電腦資訊管理。2004年,我開始接觸單眼相機,並在2008年正式成為一名接案攝影師,目前使用Canon系統進行拍攝。2016年,我愛上了美麗的水草缸,這讓我的生活多了另一層次的放鬆。每天在電腦前修圖時,能欣賞紅吱吱、綠油油的水草,彷彿多了一份平靜與愉悅。攝影與水草讓我的生活充滿了藝術與自然的交融。
連絡信箱:hello@hahasmile.com (歡迎合作提案)
DORIGO IMAGE 攝影工作室:https://dorigo-image.com
如果你喜歡我的內容,可以用行動贊助我一杯咖啡☕,支持我持續創作,也讓這個網站可以繼續營運下去喔!

若您喜歡這篇文章,歡迎按讚分享喔!
2 回復
    • 多力哥
      多力哥 says:

      你好,這篇需要會一點WP基礎的人才會操作喔。

      方式1

      function語法要加在佈景函式庫 (functions.php)

      顯示第一張圖片的語法要加在佈景的主要模板 (index.php)<--可能的名稱
      而語法貼上的位置也有一個固定的地方

      回覆

發表評論

想要留言嗎?
歡迎歡迎!

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *