3

I am trying to filter the Media Library so only media items that are uploaded by the current user OR children of the post being edited are visible. I've had no problem doing it if the conditions are both required, but I can't figure out how to OR queries.

I've found that you can define relations for inner queries like meta_query and tax_query and so on, but not the outer query. (Please note, I've tried to read extensively in the codex, but WordPress development is still very new to me, so I may be missing something obvious.)

This is as far as I've gotten:

add_filter( 'ajax_query_attachments_args', 'filterMediaLibrary', 10, 1 );
function filterMediaLibrary($query = array()) {
    $query['post_parent'] = $_POST['post_id'];
    //$query['author'] = get_current_user_id();
    return $query;
}

Both queries (post_parent and author) work separately. Is there a way to combine them so it's an additive filter rather than restrictive?

1 Answer 1

2

The only way to do it is using a query filter I think

function wpse156319_posts_where( $where, $query ) {
    global $wpdb;
    $where .= $wpdb->prepare( ' AND (' . $wpdb->posts . '.post_parent = %s OR ' . $wpdb->posts . '.post_author = %s)', $_POST['id'], get_current_user_id() );
    return $where;
}

which you just add in the ajax_query_attachments_args instead of doing anything else

function filterMediaLibrary($query = array()) {
    add_filter( 'posts_where', 'wpse156319_posts_where', 10, 2 );
    return $query;
}

Seeing as it's a one-off ajax query it shouldn't need removing.

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.