将图像从上传目录中的URL添加到媒体库

时间:2012-09-06 作者:helgatheviking

插件“视频嵌入和缩略图生成器”在从视频生成缩略图方面做得很好。它将缩略图URL保存为附件的元数据。缩略图将添加到上载目录。是否有方法获取此图像并将其添加到媒体库中,以便我可以通过image\\u downsize函数传递图像以创建不同大小的缩略图?

wp\\u insert\\u附件看起来需要文件的路径,而不是URL,还是我弄错了?如何向媒体库添加URL?

这可能是How can I get an image from the uploads dir and enter it in the media library? 但这从来没有得到任何答案。

2 个回复
最合适的回答,由SO网友:helgatheviking 整理而成

以下是我从kg_video_attachment_fields_to_save() 过滤附件\\u字段\\u以保存的函数:

    $thumb_url = $attachment[\'kgflashmediaplayer-poster\'];

    //insert the $thumb_url into the media library if it does not already exist
    if ( ! ($thumb_id = get_attachment_id_from_src( $thumb_url ) ) ) {

        $post_id = $post[\'ID\'];
        $desc = $attachment[\'post_title\'] . \' thumbnail\';

        //is image in uploads directory?
        $upload_dir = wp_upload_dir();

        if ( FALSE !== strpos( $url, $upload_dir[\'baseurl\'] ) ) {
            $wp_filetype = wp_check_filetype(basename($thumb_url), null );
            $filename = preg_replace(\'/\\.[^.]+$/\', \'\', basename($thumb_url));

            $attachment = array(
               \'guid\' => $thumb_url, 
               \'post_mime_type\' => $wp_filetype[\'type\'],
               \'post_title\' => $desc,
               \'post_content\' => \'\',
               \'post_status\' => \'inherit\'
            );
            $thumb_id = wp_insert_attachment( $attachment, basename($thumb_url), $post_id );
            // you must first include the image.php file
            // for the function wp_generate_attachment_metadata() to work
            require_once(ABSPATH . \'wp-admin/includes/image.php\');
            $attach_data = wp_generate_attachment_metadata( $thumb_id, basename($thumb_url) );
            wp_update_attachment_metadata( $thumb_id, $attach_data );
        } else { //not in uploads so we\'ll have to sideload it
            $tmp = download_url( $thumb_url );

            // Set variables for storage
            // fix file filename for query strings
            preg_match(\'/[^\\?]+\\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/\', $thumb_url, $matches);
            $file_array[\'name\'] = basename($matches[0]);
            $file_array[\'tmp_name\'] = $tmp;

            // If error storing temporarily, unlink
            if ( is_wp_error( $tmp ) ) {
                @unlink($file_array[\'tmp_name\']);
                $file_array[\'tmp_name\'] = \'\';
            }

            // do the validation and storage stuff
            $thumb_id = media_handle_sideload( $file_array, $post_id, $desc );

            // If error storing permanently, unlink
            if ( is_wp_error($thumb_id) ) {
                @unlink($file_array[\'tmp_name\']);
                return $thumb_id;
            }

            if ( $local_src = wp_get_attachment_url( $thumb_id ) ) {
                update_post_meta($post[\'ID\'], \'_kgflashmediaplayer-poster\', $local_src);
            }

        } //end sideload

    } //end get_attachment_id_from_src

    if(!is_wp_error($thumb_id)) {
        $thumb_id = intval( $thumb_id );
        update_post_meta($post[\'ID\'], \'_kgflashmediaplayer-poster-id\', $thumb_id);
    } 
视频的自定义缩略图ID现在存储在元字段中:_kgflashmediaplayer-poster-id

function get_attachment_id_from_src ($image_src) {
    global $wpdb;

    $query = "SELECT ID FROM {$wpdb->posts} WHERE guid=\'$image_src\'";
    $id = $wpdb->get_var($query);
    return $id;

}
我不喜欢get_attachment_id_from_src() 但没有内置的方法来实现这一点。我应该添加一个检查,以便如果当前src与旧源相同,则不需要运行此查询。embedder插件为每个视频创建了许多潜在的缩略图,无需将它们全部插入媒体库。。。。因此,每当保存媒体附件时,就会触发此操作,并应涵盖媒体库中已有的图像、媒体目录中但不在库中的图像以及其他服务器上的图像(这些服务器会被侧加载,并且URL会调整为新的本地URL)

SO网友:Chris_O

如果图像位于内容源中,则可以将其提取并使用media_sideload_image(); 将其导入媒体库。

此代码示例来自我的插件Media Tools. 它通过ajax的管理页面来实现这一点。它还将提取的图像设置为帖子的特色图像。post id通过ajax传递给此函数。要查看完整的代码,请参阅:http://plugins.trac.wordpress.org/browser/media-tools/trunk/media-tools.php?rev=581988

   function process_image( $post_id ) {
        $response = \'\';
        $error = 0;
        $post = get_post( $post_id );
        $img = $this->extract_image( $post );
        if( empty( $img ) ) {
            $response .=  \'No images found <br>\';
            die( sprintf( $response . \'<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors\', esc_html( $post->ID ), timer_stop(), $error = $error  > 0 ? $error : \'no\' ) );
         }
        /** @var $file string or WP_Error of image attached to the post  */
        $file = media_sideload_image( $img, (int)$post->ID );
        if ( is_wp_error( $file ) ) {
            $response .= \'<span style="color:red">Upload Error: Could not upload image. Check for malformed img src url</span><br>\';
            $error++;
        } else {

         $atts = $this->get_attach( $post->ID );
         foreach ( $atts as $a ) {
             $img = set_post_thumbnail( $post->ID, $a[\'ID\'] );
             if ( $img ) {
                  $thumb = wp_get_attachment_thumb_url( $a[\'ID\'] );
                  $response .= \'<img src="\'.esc_url( $thumb ).\'" /><br>\';
                  $response .= \'<a href="\'.wp_nonce_url( get_edit_post_link( $a[\'ID\'], true ) ).\'" >\'.get_the_title( $a[\'ID\'] ).\'</a>  Set as Featured Image</p><br>\';
                        }
                    }
                    unset( $atts );
                    unset( $a );
                }
            die( sprintf( $response.\'<br>Media tool complete (Post ID %1$s) in %2$s seconds. %3$d errors\', esc_html( $post->ID ), timer_stop(), $error = $error > 0 ? $error : \'no\' ) );
    }


    /**
     * Extracts the first image in the post content
     * @param object $post the post object
     * @return bool|string false if no images or img src
     */
    function extract_image( $post ) {
        $html = $post->post_content;
        if ( stripos( $html, \'<img\' ) !== false ) {
            $regex = \'#<\\s*img [^\\>]*src\\s*=\\s*(["\\\'])(.*?)\\1#im\';
            preg_match( $regex, $html, $matches );
            unset( $regex );
            unset( $html );
            if ( is_array( $matches ) && ! empty( $matches ) ) {
                return  $matches[2];

            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * Queries for attached images
     * @param int $post_id The post id to check if attachments exist
     * @return array|bool The 1st attached on success false if no attachments
     */
    function get_attach( $post_id ) {
        return get_children( array (
                \'post_parent\'    => $post_id,
                \'post_type\'      => \'attachment\',
                \'post_mime_type\' => \'image\',
                \'posts_per_page\'  => (int)1
            ), ARRAY_A );
    }

结束

相关推荐