如何以编程方式将特色图像设置为从外部自定义帖子

时间:2013-05-27 作者:Faisal Shehzad

我正在尝试通过PHP获取wordpress环境之外的图像并将其插入到自定义帖子中。

如何像wordpress那样将该图像移动/上载到wordpress上载目录year date文件夹格式,并根据自定义帖子将该图像设置为特色图像?

是否还要将图像上载到自定义帖子库?

下面是我的代码

$filename = $image[\'name\'];
$target_path = "../wp-content/uploads/";
$target_path = $target_path . $filename;
$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
    \'guid\' => $wp_upload_dir[\'baseurl\'] . \'/\' . basename( $filename ),
    \'post_mime_type\' => $wp_filetype[\'type\'],
    \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', basename($filename)),
    \'post_content\' => \'\',
    \'post_status\' => \'inherit\',
);
$attach_id = wp_insert_attachment( $attachment, $target_path, $post_id );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
set_post_thumbnail( $post_id, $attach_id );
我已成功将图像上载到上载目录,但无法创建年份和日期文件夹。这有什么wp功能吗??

4 个回复
SO网友:GhostToast

这不能简单地用media_sideload_image() ?

看起来很简单。唯一需要注意的是,如果您不在管理区,您必须在WordPress中包含一些库,包括:

// only need these if performing outside of admin environment
require_once(ABSPATH . \'wp-admin/includes/media.php\');
require_once(ABSPATH . \'wp-admin/includes/file.php\');
require_once(ABSPATH . \'wp-admin/includes/image.php\');

// example image
$image = \'http://example.com/logo.png\';

// magic sideload image returns an HTML image, not an ID
$media = media_sideload_image($image, $post_id);

// therefore we must find it so we can set it as featured ID
if(!empty($media) && !is_wp_error($media)){
    $args = array(
        \'post_type\' => \'attachment\',
        \'posts_per_page\' => -1,
        \'post_status\' => \'any\',
        \'post_parent\' => $post_id
    );

    // reference new image to set as featured
    $attachments = get_posts($args);

    if(isset($attachments) && is_array($attachments)){
        foreach($attachments as $attachment){
            // grab source of full size images (so no 300x150 nonsense in path)
            $image = wp_get_attachment_image_src($attachment->ID, \'full\');
            // determine if in the $media image we created, the string of the URL exists
            if(strpos($media, $image[0]) !== false){
                // if so, we found our image. set it as thumbnail
                set_post_thumbnail($post_id, $attachment->ID);
                // only want one image
                break;
            }
        }
    }
}

SO网友:hitautodestruct

尝试以下解释uploading using a path and post ID.

以下是代码(用于遗留):

/* Import media from url
 *
 * @param string $file_url URL of the existing file from the original site
 * @param int $post_id The post ID of the post to which the imported media is to be     attached
 *
 * @return boolean True on success, false on failure
 */

function fetch_media($file_url, $post_id) {
require_once(ABSPATH . \'wp-load.php\');
require_once(ABSPATH . \'wp-admin/includes/image.php\');
global $wpdb;

if(!$post_id) {
    return false;
}

//directory to import to    
$artDir = \'wp-content/uploads/2013/06\';

//if the directory doesn\'t exist, create it 
if(!file_exists(ABSPATH.$artDir)) {
    mkdir(ABSPATH.$artDir);
}

//rename the file
$ext = array_pop(explode("/", $file_url));
$new_filename = \'blogmedia-\'.$ext;

if (@fclose(@fopen($file_url, "r"))) { //make sure the file actually exists
    copy($file_url, ABSPATH.$artDir.$new_filename);


    $siteurl = get_option(\'siteurl\');
    $file_info = getimagesize(ABSPATH.$artDir.$new_filename);

    //create an array of attachment data to insert into wp_posts table
    $artdata = array();
    $artdata = array(
        \'post_author\' => 1, 
        \'post_date\' => current_time(\'mysql\'),
        \'post_date_gmt\' => current_time(\'mysql\'),
        \'post_title\' => $new_filename, 
        \'post_status\' => \'inherit\',
        \'comment_status\' => \'closed\',
        \'ping_status\' => \'closed\',
        \'post_name\' => sanitize_title_with_dashes(str_replace("_", "-", $new_filename)),                                            \'post_modified\' => current_time(\'mysql\'),
        \'post_modified_gmt\' => current_time(\'mysql\'),
        \'post_parent\' => $post_id,
        \'post_type\' => \'attachment\',
        \'guid\' => $siteurl.\'/\'.$artDir.$new_filename,
        \'post_mime_type\' => $file_info[\'mime\'],
        \'post_excerpt\' => \'\',
        \'post_content\' => \'\'
    );

    $uploads = wp_upload_dir();
            $save_path = $uploads[\'basedir\'].\'/2013/06/\'.$new_filename;

    //insert the database record
    $attach_id = wp_insert_attachment( $artdata, $save_path, $post_id );

    //generate metadata and thumbnails
    if ($attach_data = wp_generate_attachment_metadata( $attach_id, $save_path)) {
        wp_update_attachment_metadata($attach_id, $attach_data);
    }

    //optional make it the featured image of the post it\'s attached to
    $rows_affected = $wpdb->insert($wpdb->prefix.\'postmeta\', array(\'post_id\' => $post_id, \'meta_key\' => \'_thumbnail_id\', \'meta_value\' => $attach_id));
}
else {
    return false;
}

return true;
}

SO网友:Liz Eipe C

请参考以下以编程方式设置特色图像的代码。http://www.pearlbells.co.uk/code-snippets/set-featured-image-wordpress-programmatically/

function setFeaturedImages() {

$base = dirname(__FILE__);
$imgfile= $base.DS.\'images\'.DS.\'14\'.DS.\'Ascot_Anthracite-Grey-1.jpg\';
$filename = basename($imgfile);
$upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
if (!$upload_file[\'error\']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
        \'post_mime_type\' => $wp_filetype[\'type\'],
        \'post_parent\' => 0,
        \'post_title\' => preg_replace(\'/\\.[^.]+$/\', \'\', $filename),
        \'post_content\' => \'\',
        \'post_status\' => \'inherit\'
    );
$attachment_id = wp_insert_attachment( $attachment, $upload_file[\'file\'], 209 );

if (!is_wp_error($attachment_id)) {
    require_once(ABSPATH . "wp-admin" . \'/includes/image.php\');
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file[\'file\'] );
    wp_update_attachment_metadata( $attachment_id,  $attachment_data );
}

set_post_thumbnail( 209, $attachment_id );

}
}

SO网友:Simon

也许我是误解了,但你为什么要在WordPress环境之外这样做呢?复制此功能需要大量工作!WordPress不仅仅是简单地上传文件并将其放置在特定目录中,例如控制允许哪些用户上传文件,添加数据库记录以供上传,以及设置特色图像关系,对依赖于文件上载的外部插件执行操作和筛选-同时遵守站点设置(关于命名约定、媒体上载位置等)。

如果您只是想上传文件而没有登录WordPress管理部分,例如从外部站点上传文件,您可能需要查看XML-RPC API 特别是uploadFile 方法

另一种选择是自己编写一个迷你API。基本上你想做的是:

通过上传(或让服务器从指定URL下载)在服务器上获取文件使用wp_upload_dir() 获取上载目录路径和sanitize_file_name() 构造路径并将文件写入结果位置使用wp_insert_attachment() 将附件存储在数据库中(wp_check_filetype() 将有助于设置post_mime_type). 也可以选择设置post_parent 以及_thumbnail_id 元键,如果你喜欢的话wp_create_nonce() 和wp_verify_nonce() 使表单更加安全

结束