2016-11-07 61 views
1

我發現這個功能here。 我正在使用ACF pro。WordPress:設置'精選圖像'作爲第一個ACF畫廊時,保存後

更新:我添加變量根據下面的評論,這擺脫了錯誤,但功能仍然無法正常工作。

的functions.php:

說明::未定義變量:

add_action('save_post', 'set_featured_image_from_gallery'); 

function set_featured_image_from_gallery() { 
    $post = get_post(); //Edit according to comment below  
    $has_thumbnail = get_the_post_thumbnail($post->ID); 

    if (!$has_thumbnail) { 

    $images = get_field('gallery', false, false); 
    $image_id = $images[0]; 

    if ($image_id) { 
     set_post_thumbnail($post->ID, $image_id); 
    } 
    } 
} 

錯誤信息保存後(按壓 「更新」 - 按鈕)時交/應用程序/ MAMP/htdocs中/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php on line 600

注意:試圖在/ Applications/MAMP/htdocs/pf-blank中獲取非對象的屬性/ WP/WP-CONT在線600上的ent/themes/PF-Blank-theme/functions.php

警告:無法修改頭信息 - 頭文件已經發送(輸出開始於/ Applications/MAMP/htdocs/pf-blank/wp/wp-內容/主題/ PF-Blank-theme/functions.php:600),位於/Applications/MAMP/htdocs/pf-blank/wp/wp-admin/post.php在線197

警告:無法修改標題信息 -/Applications/MAMP/htdocs/pf-中已經發送的頭文件(輸出開始於/Applications/MAMP/htdocs/pf-blank/wp/wp-content/themes/PF-Blank-theme/functions.php:600)在線1174空白/ wp/wp-includes/pluggable.php

+0

首先你需要得到您的文章在$後varriable數據,然後,然後你可以使用後$> ID,您在功能上已經過去了,因此使用get_posts數據獲取所有後期數據到$ post varriable,然後嘗試添加一個'$ post = get_posts();'不起作用,用'$ has_thumbnail'周圍的foreach循環嘗試 –

+0

,也不起作用。我可以得到一個代碼示例嗎? –

回答

1

您需要傳遞參數get_posts函數通過給出參數。

試試下面的代碼:

function set_featured_image_from_gallery() { 

    $args = array('posts_per_page' => 10, 'order'=> 'ASC'); 
    $postslist = get_posts($args); 
    foreach ($postslist as $post) : 
     $has_thumbnail = get_the_post_thumbnail($post->ID); 

     if (!$has_thumbnail) { 

     $images = get_field('gallery', false, false); 
     $image_id = $images[0]; 

     if ($image_id) { 
      set_post_thumbnail($post->ID, $image_id); 
     } 
     } 
     endforeach; 
    } 

    add_action('save_post', 'set_featured_image_from_gallery'); 
+0

爲此工作:'$ postlist = get_posts($ args);'=='$ postslist = get_posts($ args);'&'if($ has_thumbnail){'== if(!$ has_thumbnail){' –

+0

@Carl Papworth對不起,你說得更詳細些?我的解決方案不適合你? –

+0

這個函數除了有一些拼寫錯誤之外,還有一些錯誤:'$ postlist'變量名不一樣,'$ has_thumbnail'應該是'!$ has_thumbnail',所以它不會改變以前設置的縮略圖。這只是爲了複製/粘貼目的。乾杯。 –