Skip to content

Instantly share code, notes, and snippets.

@eudesgit
Last active January 31, 2023 14:40
Show Gist options
  • Save eudesgit/4d08b46c7bbea7ed6d4570d31c8c0f62 to your computer and use it in GitHub Desktop.
Save eudesgit/4d08b46c7bbea7ed6d4570d31c8c0f62 to your computer and use it in GitHub Desktop.
WordPress - Uploading images to Advanced Custom Fields (AFC)
<?php
class ACF_Image_Upload {
public $post_id;
function update_acf ( ) {
$attach_id = $this->get_image_attach_id('my-image.jpg');
// Saving image
update_field('image', $attach_id, $this->post_id);
}
function get_image_attach_id ( $filename ) {
// Get the path to the upload directory.
// If it was uploaded to WP, wp_upload_dir() does the job
$wp_upload_dir = wp_upload_dir();
$full_path = $wp_upload_dir['path'] . $filename;
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype(basename($full_path), null);
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename($full_path),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename($full_path) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $full_path, $this->post_id );
return $attach_id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment