如何将上传的图片设置为特色图片WordPress

时间:2014-09-17 作者:Femi

如何将表单中上传的图像设置为帖子的特色图像。

以下是我的基本代码:

用户填写表单并上载图像。提交的表单数据显示为自定义帖子类型。上传的图片将是定制帖子的特色图片。

代码

<form method=\'post\' enctype=\'multipart/form-data\'>
    First Name: <input type=\'text\' name=\'fname\'>
    Message: <textarea name=\'message\'></textarea>
    Photo: <input type=\'file\' name=\'file\'>
    <input type=\'submit\' name=\'submit\'>
</form>

<?php if(isset($_POST[\'submit\']) && !empty($_POST)) {
//Upload Image
    require_once( ABSPATH . \'wp-admin/includes/image.php\' );
    require_once( ABSPATH . \'wp-admin/includes/file.php\' );
    require_once( ABSPATH . \'wp-admin/includes/media.php\' );
    $attachment_id = media_handle_upload(\'file\',30);
    if (is_wp_error($attachment_id)) { 
        echo \'BIG TIME ERROR\'; } 
    else { 
        echo \'BIG TIME SUCCESS\';}

//Insert Post
    $my_post = array(
    \'post_title\'    => $_POST[\'fname\'],
    \'post_content\'  => $_POST[\'message\'],
    \'post_status\'   => \'draft\',
    \'post_author\'   => 1,
    \'post_category\' => array(8,39),
    \'post_type\'      => \'my_custom_post\'
    );
    wp_insert_post( $my_post );

//Set Image as thumbnail
    set_post_thumbnail($my_post, $attachment_id); //Don\'t know what to do with this
?>
我已经做了研究,它的功能是set_post_thumbnailupdate_post_meta?

如果您能提供更多信息,我将不胜感激

1 个回复
最合适的回答,由SO网友:Sisir 整理而成

你读过set_post_thumbnail()?

对于set_post_thumbnail() 作用功能wp_insert_post() 成功后将返回post id。您可以使用该帖子id设置缩略图。

Here is the modification for your last couple of lines

$post_id = wp_insert_post( $my_post );

if(!$post_id){
    // post insertion was failed. Handle it here
}

//Set Image as thumbnail
set_post_thumbnail($post_id, $attachment_id); //Don\'t know what to do with this
这应该可以做到。

代码未测试

结束

相关推荐

Changing Gallery images size?

我正在抓取我的图库图像的URL:$gallery = get_post_gallery_images( $post ); foreach($gallery as $thumbnail) { echo $thumbnail_slideshow; } 问题是我得到的只是缩略图:image1-150x150.jpg image2-150x150.jpg image3-150x150.jpg 我想得到:image1-600x100.