【问题标题】:WordPress file "upload" from pluginWordPress 文件从插件“上传”
【发布时间】:2012-06-28 09:07:44
【问题描述】:

我正在尝试创建将帖子导入 WordPress 的插件。导入的文章 (XML) 包含“图像名称”属性,并且该图像已上传到服务器。

但是,我想让 WordPress 发挥其“魔力”并将图像导入系统(创建缩略图,将其附加到帖子,将其放在 wp-uploads 目录方案下)...我找到了功能media_handle_upload($file_id, $post_id, $post_data, $overrides) 但它需要数组 $_FILES 来填充实际上传(而且我没有上传文件 - 它已经放在服务器上)所以它不是很有用

你有什么提示吗?

谢谢

【问题讨论】:

  • 图片是否放置在正确的上传文件夹中,还是您希望将其移动到正确的位置,然后链接到帖子??
  • 它只通过 ftp 放置到服务器,它不在 wp 上传文件夹中...我希望 wordpress 在媒体库中显示图像(与帖子链接)并将其移动到相应目录...跨度>

标签: php wordpress


【解决方案1】:

检查以下脚本以获得想法。 (它确实有效。)

    $title = 'Title for the image';
    $post_id = YOUR_POST_ID_HERE; // get it from return value of wp_insert_post
    $image = $this->cache_image($YOUR_IMAGE_URL);
    if($image) {
        $attachment = array(
            'guid' => $image['full_path'],
            'post_type' => 'attachment',
            'post_title' => $title,
            'post_content' => '',
            'post_parent' => $post_id,
            'post_status' => 'publish',
            'post_mime_type' => $image['type'],
            'post_author'   => 1
        );

        // Attach the image to post
        $attach_id = wp_insert_attachment( $attachment, $image['full_path'], $post_id );
        // update metadata
        if ( !is_wp_error($attach_id) )
        {
            /** Admin Image API for metadata updating */
            require_once(ABSPATH . '/wp-admin/includes/image.php');
            wp_update_attachment_metadata
            ( $attach_id, wp_generate_attachment_metadata
            ( $attach_id, $image['full_path'] ) );
        }
    }

function cache_image($url) {
    $contents = @file_get_contents($url);
    $filename = basename($url);
    $dir = wp_upload_dir();
    $cache_path = $dir['path'];
    $cache_url = $dir['url'];

    $image['path'] = $cache_path;
    $image['url'] = $cache_url;

    $new_filename = wp_unique_filename( $cache_path, $filename );
    if(is_writable($cache_path) && $contents)
    {
        file_put_contents($cache_path . '/' . $new_filename, $contents);

        $image['type'] = $this->mime_type($cache_path . '/' . $new_filename); //where is function mime_type() ???

        $image['filename'] = $new_filename;
        $image['full_path'] = $cache_path . '/' . $new_filename;
        $image['full_url'] = $cache_url . '/' . $new_filename;
        return $image;
    }
    return false;
}

【讨论】:

    猜你喜欢
    • 2018-01-29
    • 1970-01-01
    • 2020-07-09
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多