如何通过编程将特色图片设置为来自外部的自定义帖子


13

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

像wordpress一样,如何将图像移动/上传到wordpress上传目录年日期文件夹格式,并根据自定义帖子将该图像设置为特色图像?

还要将图像上传到自定义帖子库吗?

下面是我的代码

$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功能吗??

Answers:


27

这不能简单地通过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;
            }
        }
    }
}

1
这个解决方案就像一个魅力(y)
Omar Tariq

在哪里可以添加此代码?
er.irfankhan11年

1
由于WordPress的4.8,你可以设置在第四个参数media_sideload_image'id',它会返回新的连接ID。例如:$new_att_id = media_sideload_image($image, $post_id, "image description...", 'id'); if(!is_wp_error($new_att_id)) { set_post_thumbnail($post_id, $new_att_id); }
唐·威尔逊

1

尝试使用路径和帖子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;
}

1

请参考以下以编程方式设置特色图片的代码。 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 );

}
}

0

也许我误会了,但是为什么要在WordPress环境之外进行呢?复制此功能将需要大量工作!WordPress所做的不只是简单地上传文件并将其放置在特定目录中,例如,控制允许哪些用户上传文件,添加要上传的数据库记录并设置特色图像关系,对依赖于外部插件的操作和过滤器进行操作文件上传-始终遵守网站设置(关于命名约定,媒体上传位置等)。

如果您只是想上载文件而不登录到WordPress admin部分,例如从外部站点上载文件,则可能需要查看XML-RPC API,尤其是该uploadFile方法。

另一种选择是自己编写一个迷你API。基本上,您要执行的操作是:

  1. 通过上载在服务器上获取文件(或使服务器从指定的URL下载文件)。
  2. 使用wp_upload_dir()获得的上传目录路径和sanitize_file_name()构建路径和文件写入到所得到的位置。
  3. 使用wp_insert_attachment()存储在数据库中的附件(wp_check_filetype()将成为设定有益的post_mime_type)。如果需要,还可以选择设置post_parent_thumbnail_idmeta键。
  4. 将您的API公开给外部用户,或根据需要要求登录。如果您使用的是公用的形式至少是使用wp_create_nonce()wp_verify_nonce()制作形式一点点更安全。

我正在为应用程序编写Web服务。应用程序向我发送了一个FILE数组,我想通过该FILE数组插入帖子数据和图像,我已经在数据库中插入了帖子详细信息,但卡在了图像部分。
Faisal Shehzad

检查文档wp_insert_attachment(),它应该做我想做的很多事情。如果您正在这样做,我极力劝阻在WordPress之外手动修改数据库。相反,只需查看WordPress来源并尝试确定负责添加帖子数据,处理文件上传和插入附件的部分。换句话说,我在上面的回答中概述的内容差不多。
西蒙(Simon)

@Simon我有同样的问题。您可能要上传的另一个原因是,当您有要附加到不同帖子的图像批处理作业而不是手动进行时。
hitautodestruct13年

1
@hitautodestruct:的确,当从现有站点,旧系统,数据库导出等迁移数据时,我经常这样做。我的观点是,您应该始终努力利用WordPress核心功能来完成此任务,而不仅仅是编写脚本自己将图片放置在正确的位置(这在某种程度上扩展了我所认为的问题所在)。
西蒙(Simon)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.