如何在WordPress中插入设置精选图像?

时间:2018-03-15 09:52:48

标签: php wordpress

在数据库中插入帖子工作正常。在wordpress uploads文件夹中上传文件也正常。问题是我无法在admin 设置精选图片部分设置此文件。 我需要使用我的函数 crb_insert_email_as_post 上传此文件。 我不知道什么时候我错了。 有人可以帮忙吗? 这是我更新wordpress数据库的功能

function crb_insert_email_as_post( $email ) {
$post_attr = [
    'post_type'    => 'crb_form_submission',
    'post_title'   => $email->crb_get_subject(),
    'post_content' => $email->crb_get_message(),
    'post_status'  => 'publish',
];

$post_id = wp_insert_post( $post_attr );

add_post_meta( $post_id, '_crb_sender', $email->crb_get_sender() );
add_post_meta( $post_id, '_crb_sender_email', $email->crb_get_sender_email() 
);

$attachment = array(
    'post_mime_type' => $email->crb_get_file_type(),
    'post_parent' => $post_id,
    'post_title' => '',
    'post_content' => '',
    'post_status' => 'inherit'
);

$attachment_id = wp_insert_attachment( $attachment, $email-
>crb_get_file_path(), $post_id );

require_once( ABSPATH . 'wp-admin/includes/image.php' );

$attach_data = wp_generate_attachment_metadata( $attachment_id, $email-
>crb_get_file_path() );

wp_update_attachment_metadata( $attachment_id ,  $attach_data );
}

这是我的电子邮件课程

class Email {
private $sender;
private $subject;
private $sender_email;
private $message;
private $file;

public function __construct( $sender, $subject, $sender_email, $message, $file = '' ) {
    $this->sender = $sender;
    $this->subject = $subject;
    $this->sender_email = $sender_email;
    $this->message =  $message;
    $this->file = $file;
}

public function crb_get_sender() {
    return $this->sender;
}

public function crb_get_subject() {
    return $this->subject;
}

public function crb_get_sender_email() {
    return $this->sender_email;
}

public function crb_get_message() {
    return $this->message;
}

public function crb_get_file() {
    return $this->file;
}

public function crb_get_file_type() {
    return $this->file['file']['type'];
}

function crb_get_file_path() {
    return wp_upload_dir()['path'] . '/' . $this->file['file']['name'];
}

public function crb_move_file_in_uploads() {
    if ( ! $this->file ) {
        return;
    }

    if ( ! function_exists( 'wp_handle_upload' ) ) {
        require_once( ABSPATH . 'wp-admin/includes/file.php' );
    }

    $movefile = wp_handle_upload( $this->file['file'], 'wp_handle_upload' );

    $uploadedfile = $this->file['file'];

    $upload_overrides = array( 'test_form' => false );

    $movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
}
}

1 个答案:

答案 0 :(得分:0)

我猜你错过了将其设置为精选图片的功能。

set_post_thumbnail( $post_id, $attachment_id );

之后

wp_update_attachment_metadata( $attachment_id ,  $attach_data );

你可能需要:

require_once( ABSPATH . 'wp-admin/includes/post.php' );