1

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;
}

1 Answer 1

1

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 }
8
  • It ALMOST works :) You can now see the only images from this post. One problem. I cannot upload a new image and add/select it. The upload works, but after upload I cannot press the select button bottom right.
    – Tim
    Commented Jan 16, 2020 at 10:49
  • Also, you can add jQuery('#media-attachment-filters').remove(); after changing the selected
    – Tim
    Commented Jan 16, 2020 at 10:54
  • Can you please check your console as I did it in mine and there is no issue relate to this I found. Commented Jan 16, 2020 at 10:56
  • Ah yes, it throws: jquery-migrate.js?ver=1.4.1:45 JQMIGRATE: jQuery.fn.attr('selected') might use property instead of attribute
    – Tim
    Commented Jan 16, 2020 at 11:01
  • 1
    Still doesn't work on my end. even with default theme and selecting the dropdown manually. In other words, it's not your script but my setup that's not working. Maybe you can still add jQuery('#media-attachment-filters').remove(); to your solution for other people. It removes the dropdown since it's disabled.
    – Tim
    Commented Jan 16, 2020 at 12:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.