2013-09-28 76 views
4

我想將圖片設置爲帖子的精選圖片。我在wordpress文檔中找到了這段代碼,它將圖像保存在上傳目錄中,但圖像不再被設置爲帖子的精選圖像(代碼中爲37)。如何在Wordpress上用php設置圖像爲特色圖像?

你能看一下嗎?非常感謝

<?php 
    $wp_filetype = wp_check_filetype(basename($filename), null); 
    $wp_upload_dir = wp_upload_dir(); 
    $attachment = array(
    'guid' => $wp_upload_dir['url'] . '/' . basename($filename), 
    'post_mime_type' => $wp_filetype['type'], 
    'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 
    'post_content' => '', 
    'post_status' => 'inherit' 
); 
    $attach_id = wp_insert_attachment($attachment, $filename, 37); 
    // you must first include the image.php file 
    // for the function wp_generate_attachment_metadata() to work 
    require_once(ABSPATH . 'wp-admin/includes/image.php'); 
    $attach_data = wp_generate_attachment_metadata($attach_id, $filename); 
    wp_update_attachment_metadata($attach_id, $attach_data); 
?> 

回答

3

據我所知,你想使用一個圖像作爲特色圖像上的權利? 那你爲什麼不在後期使用後端精選圖片瀏覽選項。西布朗那裏,你可以簡單地uplod形象特色和功能的圖像,你可以在你的頁面the_post_thumbnail($size, $attr);

+0

感謝,這是我正在尋找的功能:) – JojoLapin45

3

與此代碼顯示您需要添加下面一行在你的代碼的末尾:

// add featured image to post 
add_post_meta($post_id, '_thumbnail_id', $attach_id); 
相關問題