WordPress插件无法从外部API保存媒体

aiqt4smr  于 2023-11-17  发布在  WordPress
关注(0)|答案(1)|浏览(141)

我正在制作一个插件,它可以从外部API获取数据并将其存储在数据库中。我选择自定义插件的原因是,我找不到任何现有的插件可以完成我所需要的任务。我有一个功能,可以验证请求并从API get_latest_data()获取所需的数据,它是存储数据库内的数据。但问题来了,当我试图保存图像。在数据库内,我可以看到一个文件正在创建和WordPress Jmeter 板的媒体选项卡内,我可以看到一个文件,但图像不加载或渲染。下面是我的函数,应该存储图像:

function save_media_as_attachment($media_url, $post_id) {
    require_once(ABSPATH . "wp-admin" . '/includes/image.php');
    require_once(ABSPATH . "wp-admin" . '/includes/file.php');
    require_once(ABSPATH . "wp-admin" . '/includes/media.php');

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

    $temp_file = download_url($media_url);

    if (is_wp_error($temp_file)) {
        return false;
    }

    $file_name = basename($media_url);

    $file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
    $post_mime_type = 'image/jpeg'; // Default to JPEG

    if (strtolower($file_extension) === 'jpg' || strtolower($file_extension) === 'jpeg') {
        $post_mime_type = 'image/jpeg';
    } elseif (strtolower($file_extension) === 'png') {
        $post_mime_type = 'image/png';
    } elseif (strtolower($file_extension) === 'mp4') {
        $post_mime_type = 'video/mp4';
    }

    $attachment = array(
        'post_title' => sanitize_file_name($file_name),
        'post_content' => '',
        'post_status' => 'inherit',
        'post_mime_type' => $post_mime_type,
    );

    $attachment_id = wp_insert_attachment($attachment, $temp_file, $post_id);

    if (!is_wp_error($attachment_id)) {
        $attachment_data = wp_generate_attachment_metadata($attachment_id, $temp_file);
        wp_update_attachment_metadata($attachment_id, $attachment_data);

        update_post_meta($attachment_id, '_wp_attached_file', $file_name);

        @unlink($temp_file);

        return $attachment_id;
    }
    @unlink($temp_file);

    return false;
}

字符串
我已经仔细检查了我从API接收的媒体,它们都很好。我还检查了MIME类型和文件权限。

ldxq2e6h

ldxq2e6h1#

我在不同的项目中遇到过这个问题。我在下面分享我通常用来处理这个问题的函数。

<?php

function handle_attachment_from_url( $url, $attachment_title ) {
    $attachment = wp_remote_get( $url, array( 'timeout' => 300 ) );

    if ( is_wp_error( $attachment ) ) {
        return $attachment;
    }

    return upload_attachment( $attachment, $attachment_title );
}

function upload_attachment( array $data, string $filename ) {
    if ( empty( $data['body'] ) ) {
        return new WP_Error( 'empty-response', 'Empty response body!' );
    }

    $response_code = (int) $data['response']['code'] ?? 400;

    if ( $response_code > 299 ) {
        return new WP_Error( 'invalid-code', 'Response code was ' . $response_code . '!' );
    }

    $filename_parts = explode( '.', $filename );

    $filename_extension = count( $filename_parts ) > 1 ? end( $filename_parts ) : false;

    if ( $filename_extension && ! in_array( $filename_extension, array( 'pdf', 'zip', 'jpg', 'png', 'gif', 'mp4', 'wav', 'mpeg' ), true ) ) {
        $filename_extension = false;
    }

    if ( ! $filename_extension ) {
        switch ( $data['headers']['content-type'] ) {
            case 'application/pdf':
                $filename .= '.pdf';
                break;
            case 'application/zip':
                $filename .= '.zip';
                break;
            case 'image/jpeg':
                $filename .= '.jpg';
                break;
            case 'image/png':
                $filename .= '.png';
                break;
            case 'image/gif':
                $filename .= '.gif';
                break;
            case 'video/mp4':
            case 'audio/mp4':
                $filename .= '.mp4';
                break;
            case 'audio/vnd.wave':
                $filename .= '.wav';
                break;
            case 'audio/mpeg':
                $filename .= '.mpeg';
                break;
            default:
                return new WP_Error( 'invalid-file-type', 'Invalid file type!', $data['headers']['content-type'] );
        }
    }

    $upload = wp_upload_bits( $filename, null, $data['body'] );

    if ( ! empty( $upload['error'] ) ) {
        return new WP_Error( 'failed-upload', 'Attachment failed to be uploaded!', array( $filename, $upload ) );
    }

    $actual_file_path_parts = explode( '/', sanitize_file_name( $upload['file'] ) );
    $actual_file_name       = end( $actual_file_path_parts );

    $attachment = array(
        'post_mime_type' => $upload['type'],
        'post_title'     => $actual_file_name,
        'post_content'   => '',
        'post_status'    => 'inherit',
    );

    $attach_id = wp_insert_attachment( $attachment, $upload['file'], 0, true );

    if ( ! $attach_id || is_wp_error( $attach_id ) ) {
        return is_wp_error( $attach_id ) ? $attach_id : new WP_Error( 'failed-update', 'Attachment failed to be inserted!' );
    }

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

    $attach_data = wp_generate_attachment_metadata( $attach_id, $upload['file'] );

    wp_update_attachment_metadata( $attach_id, $attach_data );

    return $attach_id;
}

$example_url_to_upload = 'https://www.example.com/example.pdf';

// You could also give a dynamic file title, like
// $dynamic_filename = explode( '/', $example_url_to_upload );
// handle_attachment_from_url( $example_url_to_upload, end( $dynamic_filename ) );
// that would be handle_attachment_from_url( 'https://www.example.com/example.pdf', 'example.pdf' );
$attachment_id = handle_attachment_from_url( $example_url_to_upload, 'Example PDF' );
if ( is_wp_error( $attachment_id ) ) {
    // Handle error
    return;
}

// If no error...
// You could set it as thumbnail in a post like this assuming $post_id is the ID of the post you want to set the thumbnail for.
update_post_meta( $post_id, '_thumbnail_id', $attach_id );

字符串

相关问题