Last active
January 31, 2023 14:40
-
-
Save eudesgit/4d08b46c7bbea7ed6d4570d31c8c0f62 to your computer and use it in GitHub Desktop.
WordPress - Uploading images to Advanced Custom Fields (AFC)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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