Wordpress - 以编程方式上传帖子的特色图像

时间:2017-05-11 07:42:28

标签: php wordpress

我正在尝试创建一个脚本,允许我设置某个帖子的精选图像。由于某种原因,它无法正常工作。谁能告诉我为什么?

$post_id = ... // We get the ID from the form

if (isset($_FILES['thumbnail'])) {
    $uploaded_file = $_FILES['userfile'];
    $filename      = $uploaded_file['name'];
    $tmp_file      = $uploaded_file['tmp_name'];
    $upload_dir    = wp_upload_dir();
    $end_file      = $upload_dir['path']."/$filename";

    move_uploaded_file($tmp_file, $end_file);

    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );
    $attach_id = wp_insert_attachment($attachment, $end_file, $post_id);
    set_post_thumbnail($post_id, $attach_id);
}

1 个答案:

答案 0 :(得分:0)

保持文件上传的正确param名称是什么?

您在If语句中使用不同的参数名称,只是在下一行:

if (isset($_FILES['thumbnail'])) {
    $uploaded_file = $_FILES['userfile'];

因此,请确保从正确的参数中提取文件信息。 此外,您正在为以下代码传递错误的文件路径:

$wp_filetype = wp_check_filetype($filename, null );

应该是$end_file,而不是$filename

所以正确的代码可能如下所示:

$post_id = ... // We get the ID from the form

if (isset($_FILES['thumbnail'])) {
    $uploaded_file = $_FILES['userfile'];
    $filename      = $uploaded_file['name'];
    $tmp_file      = $uploaded_file['tmp_name'];
    $upload_dir    = wp_upload_dir();
    $end_file      = $upload_dir['path']."/$filename";

    move_uploaded_file($tmp_file, $end_file);

    $wp_filetype = wp_check_filetype($end_file, null );
    $attachment = array(
        'guid'           => $wp_upload_dir['url'] . '/' . basename( $end_file ), 
        'post_mime_type' => $wp_filetype['type'],
        'post_title'     => sanitize_file_name($filename),
        'post_content'   => '',
        'post_status'    => 'inherit'
    );
    $attach_id = wp_insert_attachment($attachment, $end_file, $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, $end_file );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    set_post_thumbnail($post_id, $attach_id);
}