Created
May 13, 2015 16:01
-
-
Save hellofromtonya/4be4785f87a16d165461 to your computer and use it in GitHub Desktop.
Restrict Media Library by User Role
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Restrict Media Library by User Role | |
* | |
* @package Restrict_Media_Library | |
* @since 1.0.0 | |
* @author hellofromTonya | |
*/ | |
/** | |
* Hook into the Posts WHere filter to restrict the Media Library | |
* if the current user is not the admin. | |
* | |
* @since 1.0.0 | |
* | |
* @return null | |
*/ | |
add_action( 'admin_init', function() { | |
if ( ! current_user_can( 'manage_options' ) ) { | |
add_filter( 'posts_where', 'build_media_library_where_sql_based_on_user_role' ); | |
} | |
} ); | |
/** | |
* Build the WHERE SQL for the Media Library based on user role | |
* | |
* @since 1.0.0 | |
* | |
* @param string $where_sql | |
* @return string | |
*/ | |
function build_media_library_where_sql_based_on_user_role( $where_sql ) { | |
if ( ! isset( $_POST['action'] ) || 'query-attachments' != $_POST['action'] ) { | |
return $where_sql; | |
} | |
// Get all the user IDs for this current user's role | |
$user_ids = get_user_ids_based_on_current_user_role(); | |
if ( false === $user_ids ) { | |
return $where_sql; | |
} | |
// Sanitize the IDs | |
sanitize_user_ids( $user_ids ); | |
// Modify the WHERE SQL statement and return | |
return sprintf( '%s AND post_author IN ( %s )', $where_sql, implode( ',', $user_ids ) ); | |
} | |
/** | |
* Get all of the user IDs based on the current user's role | |
* | |
* @since 1.0.0 | |
* | |
* @return array|bool | |
*/ | |
function get_user_ids_based_on_current_user_role() { | |
global $current_user; | |
$user_ids = get_users( array( | |
'role' => $current_user->roles[0], | |
'orderby' => 'ID', | |
'fields' => 'ID', | |
) ); | |
return is_array( $user_ids ) && ! empty( $user_ids ) ? $user_ids : false; | |
} | |
/** | |
* Sanitize the user IDs | |
* | |
* @since 1.0.0 | |
* | |
* @param array $user_ids Passed by reference | |
*/ | |
function sanitize_user_ids( array &$user_ids ) { | |
global $wpdb; | |
foreach ( $user_ids as $key => $id ) { | |
$user_ids[ $key ] = $wpdb->prepare( '%d', $id ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment