I just solve this using this:
// Ensure wp.media.frame exists before modifying
if (wp.media && wp.media.frame) {
var library = wp.media.frame.state().get('library');
// Set custom filter (your_key) and refresh media items
library.props.set({
your_key: selectedValue
});
}
And create custom WordPress pre_get_posts like this:
public function pre_get_posts_filter( $query )
{
$request_data = isset( $_REQUEST[ 'query' ] ) && is_array( $_REQUEST[ 'query' ] )
? array_map( 'sanitize_text_field', wp_unslash( $_REQUEST[ 'query' ] ) )
: [ ];
$your_key = $request_data[ 'your_key' ];
if ( empty( $your_key) ) {
$your_key = 'all';
}
if ( $your_key === 'all' ) {
return; // Show all posts (no filtering)
} elseif ( $your_key === 'unassigned' ) {
$query->set( 'post__not_in', AttachmentModel::getAssignedAttachmentIds() ?? [ ] );
} else {
$attachment_ids = AttachmentModel::getAttachmentListOfFolder( intval( $your_key ) );
if ( ! empty( $attachment_ids ) ) {
$query->set( 'post__in', $attachment_ids );
// Set post statuses based on post type
$query->set( 'post_status', $query->get( 'post_type' ) === 'attachment' ?
[ 'inherit', 'private', 'publish' ] :
[ 'publish', 'pending', 'draft', 'private' ]
);
} else {
$query->set( 'post__in', [ 0 ] ); // Return no posts if folder is empty
}
}
}