Skip to content

Instantly share code, notes, and snippets.

@twentyfortysix
Created August 26, 2020 17:22
Show Gist options
  • Save twentyfortysix/89583d76e359bc7ecdffbd90f06b563f to your computer and use it in GitHub Desktop.
Save twentyfortysix/89583d76e359bc7ecdffbd90f06b563f to your computer and use it in GitHub Desktop.
import post images to acf gallery
<?php
// field id must be the ACF ID
function post_images_to_ACF_gallery($post_type, $field_id){
$args = array(
'post_status' => 'publish',
'post_type' => $post_type,
'posts_per_page' => -1,
'fields' => 'ids'
);
$the_query = new WP_Query( $args );
if ($the_query->have_posts()) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
$images = get_all_post_attachments($the_query->post);
$ids = array();
foreach ($images as $i) {
$ids[] = $i->ID;
}
update_field($field_id, $ids, $the_query->post);
}
}
}
function get_all_post_attachments($id){
$images = '';
$g_args = array(
'post_parent' => $id,
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_mime_type' => 'image',
'order' => 'ASC',
'orderby' => 'menu_order'
);
$attachments = get_children($g_args);
return $attachments;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment