Add an image gallery to a custom post type?

I am pulling data from an external web service into a custom post type. This data includes images. How can I create an image gallery, add some existing attachments to it, and associate it with a post?

What I was hoping to find is something like a set_post_gallery counterpart to the get_post_gallery function, but I can’t find anything like it in the codex, on google, or in wp-includes/media.php.

This is how I set up the attachments:

$attachment = [
  'guid' => wp_upload_dir()[ 'url' ] . '/' . basename( $path ),
  'post_mime_type' => wp_check_filetype( basename( $path ), null )[ 'type' ],
  'post_title' => "$mlsNum $id",
  'post_content' => '',
  'post_status' => 'inherit'
];

$attachmentId = wp_insert_attachment( $attachment, $path, $this->postId );

// Generate attachment metadata and create resized images.
wp_update_attachment_metadata( $attachmentId, wp_generate_attachment_metadata( $attachmentId, $path ));

And this is how I am trying to retrieve the gallery for the theme:

$gallery = get_post_gallery( $post, false );
var_dump( $gallery );
var_dump( $post );

$post is defined, and $gallery is false. I was under the impression that wp_insert_attachment would create a gallery for the post and add the attachment to it, but apparently this is not the case. If it was, then that would cause other problems for me when I go to attach a PDF to the post.

Solutions Collecting From Web of "Add an image gallery to a custom post type?"

When you just have raw image files, that you want to assign to a post, wp_insert_attachment will do the job.

With attachments already present in your database you can use wp_update_post to set the attachment’s post_parent.
Like this:

wp_update_post( array(
    'ID' => $attachment_id,
    'post_parent' => $parent_post_id,
));

To recieve a post’s attachments you can use get_children.

$args = array(
    'post_parent' => $parent_post_id,
    'post_type' => 'attachment',
);
$attachments = get_children( $args );

If you insist on using get_post_gallery– that will only return image attachments—you should add the [gallery] shortcode to your parent post content.

There’s a great PHP solution here which will add the gallery editor to the custom post type editor – great, if like me, you are creating custom post types using PHP and importing data using WPAllImport. In this case, I want to ensure I use the default gallery so I can allow my clients to edit/add/delete imported images.

The code below adds the gallery editor to your custom post type editor interface:

https://gist.github.com/alexdunae/897503