Post edit - Media Library - Only get images from current post

I've got a few ACF Image fields for posts And I want to only query the images in the media library browser already uploaded and used on the current post. In other words, when opening the media library in a image field I only want to see the images of this post.

This is what I came up with. But it doesn't work.

  • I can upload a image to one field
  • Then in second field I don't see the image from the first field.
  • (also after saving the post)
  • It now says no items found

This is my code:

add_filter('ajax_query_attachments_args', 'show_current_post_attachments', 10, 1);

function show_current_post_attachments($query = array())
{
    $post_id = $_POST['post_id'] ;
    $query['post__in'] = [$post_id];

    return $query;
}

Topic attachment-fields-to-edit advanced-custom-fields media-library attachments media Wordpress

Category Web


This will lock uploads to “Uploaded to this post” and will not show “All media items” or other options in WordPress media panels.

Add this code to your function.php file

    add_action( 'admin_footer-post-new.php', 'firmasite_mediapanel_lock_uploaded' );
    add_action( 'admin_footer-post.php', 'firmasite_mediapanel_lock_uploaded' );
    function firmasite_mediapanel_lock_uploaded() { ?>
      <script type="text/javascript">
        jQuery(document).on("DOMNodeInserted", function(){
            // Lock uploads to "Uploaded to this post"
            jQuery('select.attachment-filters [value="uploaded"]').attr( 'selected', true ).parent().trigger('change');
            jQuery('#media-attachment-filters').remove();
        });
      </script>
    <?php }

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.