ACF图像字段采用post->ID
已上载附件的。这就是你应该传递给的$request->get_param(\'image\');
下面是我在通过API插入CPT时使用的代码。我正在发送一个带有自定义字段值的POST请求。其中一个字段是上传的图像URL,附加到CPT,标记为特色,也设置为ACF字段。
add_action("rest_insert_mycpt", function (\\WP_Post $post, $request, $creating) {
$metas = $request->get_param("meta");
if (is_array($metas)) {
foreach ($metas as $name => $value) {
# Repeatable Field (extra code just in case it helps someone)
if( $name == \'bookmarks\' ) {
$save = [];
foreach( $value as $uri ) {
$save[] = array(\'url\' => $uri );
}
update_field($name, $save, $post->ID);
}
# Image field
elseif( $name == \'img\' ) {
# $value here is an URL
$save = getImageURL($value, $post->ID, $metas[\'file_name\']);
update_field($name, $save, $post->ID);
}
# Other fields
else update_field($name, $value, $post->ID);
}
}
}, 10, 3);
# Upload image from URL
# @return Attachment ID
# wordpress.stackexchange.com/a/50666
function getImageURL( $img_url, $post_id, $name ){
if( !function_exists( \'wp_generate_attachment_data\' ) )
require_once(ABSPATH.\'wp-admin/includes/image.php\');
# Upload file
$extension = getExtension($img_url);
$filename = "$name.$extension";
$uploaddir = wp_upload_dir();
$uploadfile = $uploaddir[\'path\'] . \'/\' . $filename;
$contents= file_get_contents($img_url);
$savefile = fopen($uploadfile, \'w\');
fwrite($savefile, $contents);
fclose($savefile);
# Insert into library
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
\'post_mime_type\' => $wp_filetype[\'type\'],
\'post_title\' => $filename,
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'post_parent\' => $post_id
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
$imagenew = get_post( $attach_id );
$fullsizepath = get_attached_file( $imagenew->ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $fullsizepath );
wp_update_attachment_metadata( $attach_id, $attach_data );
# Set as Featured Image
set_post_thumbnail( $post_id, $attach_id );
# Generate sizes: wordpress.stackexchange.com/a/8085
$image_sizes = get_intermediate_image_sizes();
foreach ($image_sizes as $size){
image_make_intermediate_size($uploadfile, $size[\'width\'], $size[\'height\'], false);
}
return $attach_id;
}
# Get extension from string containing filename.ext
function getExtension($filename){
$filename = explode(\'?\', $filename)[0];
return substr($filename,strrpos($filename,\'.\')+1);
}