Home › Forums › Backend Issues (wp-admin) › ACF file field with wp_insert_post function › Reply To: ACF file field with wp_insert_post function
i try to modify these functions (get here)
https://www.pearlbells.co.uk/insert-update-acf-image-repeater-field-programmatically/
function uploadImages( $files ) {
$imgAcfIds = array();
foreach($files as $imgfile) {
$filename = basename($imgfile);
$upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
if (!$upload_file['error']) {
$wp_filetype = wp_check_filetype($filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => 251,
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => '',
'post_status' => 'inherit',
'post_author' => 2,
'post_category' => array(9)
);
$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], 251 );
// get attachment id for acf field
$imgAcfIds[] = array('documento' => $attachment_id);
echo 'Attachment Id :'.$attachment_id .PHP_EOL;
if (!is_wp_error($attachment_id)) {
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
wp_update_attachment_metadata( $attachment_id, $attachment_data );
}
}
}
echo '<pre>';
print_r($imgAcfIds);
$post_id = wp_insert_post( wp_slash($attachment) );
update_field( 'field_5d78c5acf0ff3', $imgAcfIds , 251 );
}
function readDataFromImageFolder() {
$imageFolderName = 14;
$base = dirname(__FILE__);
$dirname = $base.'/images/'.$imageFolderName;
$files = array();
if (!file_exists($dirname)) {
echo "The directory $dirname not exists.".PHP_EOL;
exit;
} else {
echo "The directory $dirname exists.".PHP_EOL;
$dh = opendir( $dirname );
while (false !== ($filename = readdir($dh))) {
if ($filename === '.' || $filename === '..') continue;
$files[] = $dirname.$filename;
}
uploadImages( $files );
}
// echo '<pre>';
// print_r($files);die();
}
but don’t work my file field name is documento my file field key is field_5d78c5acf0ff3a
thanks a lot
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.