Support

Account

Home Forums ACF PRO Dynamically restrict media modal attachments

Solving

Dynamically restrict media modal attachments

  • Hello,

    I have created a Repeater which contains a Relationship field (restricted to 1 post) and an Image field. I want to dynamically restrict the attachments shown in the Image’s media modal by the ID of the post selected in the Relationship (and not by the main post to which the fields belong to).

    Is this possible and if yes what would be the best approach?

    Thanks for your help!

  • Hi @verde

    You should be able to do it by using the “pre_get_posts” hook like this:

    add_action('pre_get_posts','my_acf_image_change_query');
    function my_acf_image_change_query( $wp_query_obj ) {
     
        // only do this on certain field
        if( isset($_POST['query']) && $_POST['query']['_acfuploader'] == 'field_1234567890abc' ){
            
            // get the current post ID
            $post_id = $_POST['post_id'];
            
            // get the relationship raw value
            $relationship = get_field('custom_field_name', $post_id, false);
            
            // set the parent query
            $wp_query_obj->set( 'post_parent__in', $relationship );
        }
        
    }

    Where “field_1234567890abc” is the field key.

    I hope this helps 🙂

  • Hi @acf-support and thanks for your help so far.

    I didn’t think about using pre_get_posts so that’s an interesting approach, however the problem is the relationship field is inside of a repeater (so there’s more than one) and I want to be able to do this for _acfuploader fields in each repeater. So custom_field_name would need to be the relationship field that belongs to the same repeater row as the uploader.

    Not sure if that’s possible using a query filter.

  • Hi @verde

    I’m afraid this is not possible. That’s because you want to get the data before it’s saved in the database. That means that you need to use AJAX to post and get the new data. But the image field has its own AJAX to show the media library modal window and post the required data.

    If you can pass the current row data along with the image field AJAX, then you can do what you after. But to do that, you need to modify the core files.

    I hope this makes sense 🙂

  • @acf-support I was afraid that’s going to be the answer. I knew it had to be an AJAX solution and couldn’t find a way after looking into your core JS code, that’s why I asked here in case I was missing something.

    I guess they will have to manually go through (or search) attachments to select one belonging to the specific post, I was hoping I can make it easier.

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Dynamically restrict media modal attachments’ is closed to new replies.