首页 > 解决方案 > Wordpress 从 url 设置缩略图而不是下载到媒体

问题描述

我有一个用于 wordpress 的自动 RSS 插件,这个插件正在将图像下载到我的媒体库。有没有办法修改此代码以不下载图像只是通过其网址显示图像?喜欢自动插入图片的网址。

非常感谢您的帮助

 * Download image from url
 * since 1.0.0
 *
 * @param $url
 *
 * @return bool|int
 */
function wpcp_download_image( $url, $description = '' ) {
    $raw_url  = $url;
    $url      = explode( '?', esc_url_raw( $url ) );
    $url      = $url[0];
    $get      = wp_remote_get( $raw_url );
    $headers  = wp_remote_retrieve_headers( $get );
    $type     = isset( $headers['content-type'] ) ? $headers['content-type'] : null;
    $types    = array(
        'image/png',
        'image/jpeg',
        'image/gif',
    );
    $file_ext = array(
        'image/png'  => '.png',
        'image/jpeg' => '.jpg',
        'image/gif'  => '.gif',
    );
    if ( is_wp_error( $get ) || ! isset( $type ) || ( ! in_array( $type, $types ) ) ) {
        return false;
    }
    $file_name = basename( $url );
    $ext       = pathinfo( basename( $file_name ), PATHINFO_EXTENSION );

    if ( $ext === '' ) {
        $file_name .= $file_ext[ $type ];
    }

    $mirror     = wp_upload_bits( $file_name, '', wp_remote_retrieve_body( $get ) );
    $attachment = array(
        'post_title'     => $file_name,
        'post_mime_type' => $type,
        'post_content'   => $description,
    );

    if ( empty( $mirror['file'] ) ) {
        return false;
    }

    $attach_id = wp_insert_attachment( $attachment, $mirror['file'] );

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

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

    return $attach_id;
}

标签: wordpress

解决方案


推荐阅读