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 shortcode to your parent post content.

Leave a Comment