3

I created my own API using Wordpress Rest-API. I successfully saved all data in wordpress backend but I don't know how to get and save the data if file/image.

    register_rest_route( 'mlcs/v1', '/save_data', array(
        'methods' => 'POST',
        'callback' => array( $this, 'save_data_post' ),
        'args' => array(
            'name' => array(
                'required' => true,
                'type' => 'string',
            ),
            'image' => array(
                'required' => true,
                'type' => 'string',
            ),
        )
    ) );

public function save_data_post( $request ) {
   $name = $request->get_param('name');
   $image = $request->get_param('image');

   //save the data in ACF
   update_field('name_field', $name ); //text type

   //not saving
   update_field('image_field', $image ); //image type

}
5
  • Are you using an Image Field Type in ACF? Could you use a Text Field Type and save the image URL to this instead?
    – junkrig
    Jul 24, 2018 at 6:02
  • @junkrig, yes I'm using image type in acf. I can't use text type because the image must save to wordpress media from the local. Jul 24, 2018 at 6:48
  • Just a few more questions :-) So you're using the API to save data to the WordPress back end? As part of this, you are saving an image. Are you uploading the image to the WordPress media library first? If you are, can you use the attachment id of the image in the update_field function? In your example above, $image is a string, what would an example value of $image be?
    – junkrig
    Jul 24, 2018 at 7:25
  • to save a image with the REST API, use the endpoint wp-json/wp/v2/media. you will received the media identifier to save in the field image.
    – mmm
    Jul 24, 2018 at 21:13
  • Interesting code samples here: WP Rest API - Upload media without saving attachment post
    – brasofilo
    Nov 8, 2020 at 1:06

1 Answer 1

1

ACF Image field takes the post->ID of the uploaded attachment. That's what you should be passing to $request->get_param('image');

Here's the code I'm using for a when a CPT is inserted via API. I'm sending a POST request with custom fields values. One of the fields is an image URL which is uploaded, attached to the CPT, marked as Featured and also set as an ACF field.

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.