Created
September 26, 2022 21:41
-
-
Save MadtownLems/8842cafd4ee37427bbe607c4ad1d6071 to your computer and use it in GitHub Desktop.
user_has_cap difference in Classic and Block Editors
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 | |
/* | |
Plugin Name: Block Editor vs Classic user_has_cap proof of concept | |
Description: This plugin compares the user_has_cap filter functionality in the Classic and Block editors. It intends to allow Authors the ability to edit pages they are the author of. | |
Version: 1 | |
Author: Jason LeMahieu | |
Author URI: https://jasonlemahieu.com | |
*/ | |
/* When used in the Classic Editor, Authors can edit pages they are the author of. | |
When used in the Block Editor, Authors can only "Submit for Review". they can not edit / save their changes */ | |
add_filter( 'user_has_cap', 'ext_block_vs_classic_filters_test', 10, 3 ); | |
/** | |
* | |
* | |
* @param array $allcaps All the capabilities of the user | |
* @param array $cap [0] Required capability | |
* @param array $args [0] Requested capability | |
* [1] User ID | |
* [2] Associated object ID | |
**/ | |
function ext_block_vs_classic_filters_test( $allcaps, $cap, $args ) { | |
// allow authors to edit their own Pages | |
switch ( $args[0] ) { | |
case 'edit_post': | |
$post_author_id = get_post_field( 'post_author', $args[2] ); | |
$current_user_id = get_current_user_id(); | |
if ( $post_author_id == $current_user_id ) { | |
$allcaps[$cap[0]] = true; | |
} | |
break; | |
case 'edit_pages': | |
// args 2 is the associated object ID | |
if ( isset( $args[2] ) && $args[2] ) { | |
$post_author_id = get_post_field( 'post_author', $args[2] ); | |
$current_user_id = get_current_user_id(); | |
// asking about a specific page, so grant edit access if they arer an author of it | |
if ( $post_author_id == $current_user_id ) { | |
$allcaps[$cap[0]] = true; | |
$allcaps['edit_published_pages'] = true; | |
$allcaps['edit_published_posts'] = true; | |
$allcaps['edit_others_posts'] = true; | |
} | |
} else { | |
// they've asked about the idea in general. say yes but it doesn't necessarily let them edit ALL pages. If they can edit Posts in the abstract, they can edit pages in the abstract | |
if ( isset( $allcaps['edit_posts'] ) && $allcaps['edit_posts'] ) { | |
$allcaps[$cap[0]] = true; | |
} | |
} | |
break; | |
case 'edit_published_pages': | |
$allcaps[$cap[0]] = true; | |
break; | |
// For assistance in debugging | |
case 'view_query_monitor': | |
if ( is_user_logged_in() ) { | |
$allcaps[$cap[0]] = true; | |
} | |
break; | |
}; | |
return $allcaps; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment