Skip to content

Instantly share code, notes, and snippets.

@mannieschumpert
Last active August 2, 2020 13:15
Show Gist options
  • Save mannieschumpert/8886289 to your computer and use it in GitHub Desktop.
Save mannieschumpert/8886289 to your computer and use it in GitHub Desktop.
Code Examples from Andrew Nacin's "Current User Can Watch This Talk"
<?php
// If you can edit pages, you can edit widgets
add_filter( 'user_has_cap',
function( $caps ) {
if ( ! empty( $caps['edit_pages'] ) )
$caps['edit_theme_options'] = true;
return $caps;
} );
<?php
// Give secondary "administrators" less control:
add_filter( 'user_has_cap',
function( $caps, $cap, $args ) {
$user_id = $args[1];
$user = new WP_User( $user_id );
$email = $user->user_email;
if ( $email != get_option('admin_email') )
$caps['manage_options'] = false;
return $caps;
}, 10, 3 );
<?php
// Users can edit coments, for 30 minutes:
add_filter( 'map_meta_cap',
function( $caps, $cap, $user_id, $args ) {
if ( $cap !== 'edit_comment' )
return $caps;
$comment_id = $args[1];
$c = get_comment( $comment_id );
$user_id = $c->user_id;
$time = strtotime( $c->comment_date_gmt );
$window = strtotime( '-30 minutes' );
if ( $user_id && $time > $window )
return array(); // No cap required!
return $caps;
}, 10, 3 );
<?php
// Don't let anyone delete users:
add_filter( 'map_meta_cap',
function( $required_caps, $cap ) {
if ( 'delete_user' == $cap || 'delete_users' == $cap )
$required_caps[] = 'do_not_allow';
return $required_caps;
}, 10, 2, );
<?php
// Only administrators can delete published posts:
add_filter( 'map_meta_cap',
function( $required_caps, $cap ) {
if ( 'delete_post' == $cap )
$required_caps[] = 'manage_options';
return $required_caps;
}, 10, 2 );
<?php
// Don't allow file changes via the UI:
add_filter( 'map_meta_cap',
function( $required_caps, $cap ) {
if ( in_array( $cap, array(
'edit_themes',
'edit_plugins',
'update_themes',
'update_plugins',
'install_themes',
'install_plugins',
'update_core'
) ) )
$required_caps[] = 'do_not_allow';
return $required_caps;
}, 10, 2 );
// Built into core: (add to wp-config)
// deny edit_themes, edit_plugins
define( 'DISALLOW_FILE_EDIT' true );
// deny all file changes
define( 'DISALLOW_FILE_MODS' true );
<?php
// Require editors to approve posts:
add_filter( 'map_meta_cap',
function( $required_caps, $cap ) {
if ( $cap == 'publish_post' || $cap == 'publish_posts' )
$required_caps[] = 'edit_others_posts';
return $required_caps;
}, 10, 2 );
<?php
// Where you are assigning *_books capabilities to users:
register_post_type( 'book', array(
...
'capability_type' => 'book',
// Map read_post, edit_post, etc.
'map_meta_cap' => true,
...
) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment