I have found a code to automatically update media attachment to be attached to the current post it was uploaded to :
<?php
add_action('save_post', 'update_image_data');
function update_image_data($post_id){
$images = get_post_meta($post_id, 'mg_projet_galerie_images', true);
if(!empty($images)){
foreach($images as $image){
wp_update_post(array('ID' => $image, 'post_parent' => $post_id));
}
}
}
?>
It would be nice to have this feature natively. For example, in Bricks Builder you could query the medias attached to the current post this way : https://academy.bricksbuilder.io/article/query-loop/#media-query
At the moment, if medias are not attached to the post, then you can not query them without adding more custom code such as this one (it was given to me by Bricks support - replace with your own ID and custom field names) :
<?php
add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
if ( $element_id !== 'yeamho') return $query_vars;
$gallery_images = (array) rwmb_meta( 'mg_projet_galerie_images', ['size' => 'full'] );
$gallery_images_ids = array_keys($gallery_images);
// if no gallery images, set empty string array
$gallery_images_ids = count($gallery_images_ids) > 0 ? $gallery_images_ids : [''];
$query_vars['post__in'] = $gallery_images_ids;
return $query_vars;
}, 10, 3 );
?>