从代码设置 post 缩略图失败

Setting the post thumbnail from code fails

我有一个未完成的版本,用于从 base64 编码图像(来自 API)设置 post 缩略图,我当时没有使用它,但现在我需要它。

function attach_image ( $base64, $post_id, $filename ) {

    if ( empty($base64) ) {
        return false;
    }

    $upload_dir = wp_upload_dir();
    $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    $decoded = base64_decode($base64) ;
    $hashed_filename = md5( $filename . microtime() ) . '_' . $filename;

    $image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );

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

    $wp_filetype = wp_check_filetype(basename($filename), null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $hashed_filename, $parent_id );

    $attach_data = wp_generate_attachment_metadata( $attach_id, $hashed_filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}

这差不多行得通了,

但问题是, 如果保存的图片是:

wp-content/uploads/2019/09/0acaa00c73c27baa3277ff22ba5acf05_xk35480.jpg

post 缩略图 url 是:

wp-content/uploads/xk35480.jpg

请注意,年、月和散列都丢失了。所以很明显缩略图 url returns 404

所以问题是,你能发现问题吗?

我能够通过在 wp_insert_attachmentwp_generate_attachment_metadata 函数前添加 wp_upload_dir()['path'].'/' 来使其工作,但我想知道它是否可以完成 "better"

function attach_image ( $base64, $post_id, $filename ) {

    if ( empty($base64) ) {
        return false;
    }

    $upload_dir = wp_upload_dir();
    $upload_path = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
    $decoded = base64_decode($base64) ;
    $hashed_filename = md5( $filename . microtime() ) . '_' . $filename;

    $image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );

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

    $wp_filetype = wp_check_filetype(basename($filename), null );
    $attachment = array(
        'post_mime_type' => $wp_filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, wp_upload_dir()['path'].'/'.$hashed_filename, $post_id );

    $attach_data = wp_generate_attachment_metadata( $attach_id, wp_upload_dir()['path'].'/'.$hashed_filename );
    wp_update_attachment_metadata( $attach_id, $attach_data );

    add_post_meta($post_id, '_thumbnail_id', $attach_id, true);
}