2016-08-13 31 views
2

我試圖從帖子內容添加精選圖片。我的想法是將內容的第一張圖片設置爲帖子的精選圖片。通過博客內容以編程方式設置精選圖像

我寫這在我的funtions.php

add_action('publish_post', 'auto_featured_image_publish_post'); 
     function auto_featured_image_publish_post($post, $post_id) { 
      $thumnail_id = //something I need help with 
      set_post_thumbnail($post, $thumbnail_id); 
     } 

這只是一個想法,我要怎麼做。

請幫忙。由於

回答

1

檢查這個網址

https://www.gavick.com/blog/wordpress-quick-tip-4-automatically-set-the-first-post-image-as-a-featured-image

或者您可以使用此代碼從任何HTML代碼得到的第一個圖像的URL

<?php 
$postcontent = ""; 
preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $postcontent, $image); 
// you can use the exist pattern or use this 
// '/< *img[^>]*src *= *["\']?([^"\']*)/i' 
echo $image['src']; 
?> 
+1

感謝您的快速幫助。 我想我需要輸入圖像附件ID才能正常工作。你有什麼想法嗎? thumbnail_id必須是整數。 https://codex.wordpress.org/Function_Reference/set_post_thumbnail –

+1

檢查此網址https://www.gavick.com/blog/wordpress-quick-tip-4-automatically-set-the-first-post-image-as -a-featured-image – Mostafa

+1

謝謝Mostafa Bhai。你救了我的一天:) –

相關問題