如何用PHP设置特色图片(缩略图)?

时间:2016-06-18 作者:Picki

我正在使用创建帖子wp_insert_post(), 但这些帖子没有特色图片。

我有帖子ID和服务器上图像的路径,如何将它们设置为特色图像?

EDIT :我添加了代码来发布一篇文章。只需添加缩略图(特色图像)

imagePath= ABSPATH . "wp-content\\uploads\\image\\my_image.jpg";
publication($titre, $content, $categriesID, $tags);


function publication ($titre, $content, $categories, $tags){
    $user_id = get_current_user_id();

    $my_post = array(
        \'post_title\'    => $titre,
        \'post_content\'  => $content,
        \'post_status\'   => \'publish\',
        \'post_author\'   => $user_id,
        \'post_category\' => $categories,
        \'tags_input\'      => $tags
     );

    $post_ID = wp_insert_post( $my_post );
}

1 个回复
SO网友:Picki

我很自豪地宣布,由于@cjbj的良好建议,我找到了解决方案。我把代码粘贴在这里。我知道这会帮助别人。

此外,我使用了函数preg_quote 保护图像的路径。

protected_path = preg_quote($filename);
这段代码非常有效。
// $filename should be the path to a file in the upload directory.
$filename = \'/path/to/uploads/2013/03/filename.jpg\';

// The ID of the post this attachment is for.
$parent_post_id = 37;

// Check the type of file. We\'ll use this as the \'post_mime_type\'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
    \'guid\'           => $wp_upload_dir[\'url\'] . \'/\' . basename( $filename ), 
    \'post_mime_type\' => $filetype[\'type\'],
    \'post_title\'     => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $filename ) ),
    \'post_content\'   => \'\',
    \'post_status\'    => \'inherit\'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $parent_post_id, $attach_id );