function custom_gallery_metabox() {
add_meta_box(
'custom_gallery_metabox',
'Custom Gallery',
'render_custom_gallery_metabox',
'post',
'normal',
'high'
);
}
add_action('add_meta_boxes', 'custom_gallery_metabox');
function render_custom_gallery_metabox($post) {
// Retrieve saved image IDs
$image_ids = get_post_meta($post->ID, '_custom_gallery', true) ?: [];
?>
$image_id,
'post_parent' => $post_id
]);
}
}
}
}
add_action('save_post', 'save_custom_gallery_metabox');
function remove_gallery_attachment() {
// Check for nonce and permissions if needed
$image_id = intval($_POST['image_id']);
$post_id = intval($_POST['post_id']);
if ($image_id && $post_id) {
// Update the attachment to remove it from the post
wp_update_post([
'ID' => $image_id,
'post_parent' => 0 // Detach the image
]);
}
wp_die(); // This is required to properly terminate the AJAX request
}
add_action('wp_ajax_remove_gallery_attachment', 'remove_gallery_attachment');
// Display the custom gallery on the front end
$image_ids = get_post_meta(get_the_ID(), '_custom_gallery', true);
if ($image_ids) {
echo '';
foreach ($image_ids as $image_id) {
echo wp_get_attachment_image($image_id, 'large');
}
echo '
';
}