Wordpress远程上传并为多个图像添加postmeta

时间:2015-11-13 08:29:02

标签: php wordpress metadata

我需要从远程服务器复制图像,并在wordpress中将多个值添加到自定义post meta。例如,它应该是那样的;

custom_meta | 123,456,124,786,653

我使用下面的代码来获取文件并将其添加到上传文件夹中;

code:1
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($thumb);
$filename = $thumb_name;
if(wp_mkdir_p($upload_dir['path']))
$file = $upload_dir['path'] . '/' . $filename;
else
$file = $upload_dir['basedir'] . '/' . $filename;
file_put_contents($file, $image_data);

$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', $filename ),
'post_content' => '',
'post_status' => 'inherit',
'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename )
);

$attach_id = wp_insert_attachment( $attachment, $file, $the_post_id );
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );

code:2
add_post_meta( $the_post_id, '_thumbnail_id', $attach_id );

它适用于一个图像文件。但是如何更改此代码以添加多个$ thumb和$ attach_id for add_post_meta line?

我现在正在做的是复制代码:1次4次并更改其变量名称。然后我得到5 $ attach_ids($ attach_id,$ attach_id2,$ attach_id3,$ attach_id4,$ attach_id5)。

然后我设置一个变量;

$attach_ids = array($attach_id,$attach_id2,$attach_id3,$attach_id4,$attach_id5);

然后更改代码:'to;

add_post_meta( $the_post_id, '_thumbnail_id', $attach_ids );

并为该键添加值,如;

a:4:{i:0;i:22695;i:1;i:22696;i:2;i:22697;i:3;i:22698;}

0 个答案:

没有答案