Skip to content

Instantly share code, notes, and snippets.

@Dragooon
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dragooon/9683271 to your computer and use it in GitHub Desktop.
Save Dragooon/9683271 to your computer and use it in GitHub Desktop.
Proof of Concept for per-post roles and capabilities
<?php
/**
* Proof of concept for per-post roles and capabilities
*
* The meta is stored for a page under _post_capabilities postmeta as an array having ->
* [<user_id>] => array(
* 'user_id' => ID of the user
* 'role' => <name of the role>
* 'capabilities' => (array) <list of custom capabilities an admin might want to assign>
* )
*
* @author Shitiz "Dragooon" Garg <mail@dragooon.net>
*/
/**
* Plugin Name: Dragooon's Proof of Concept
* Description: POC for per-post roles and capabilities
* Author: Shitiz Garg (Dragooon)
* Author URI: http://smf-media.cmm
* Version: 0.0.1
* Text Domain: poc
* Domain Path: /languages/
*/
add_filter( 'user_has_cap', 'poc_user_has_cap', 99, 3 );
$postmeta = array(
2 => array(
'user_id' => 2,
'role' => 'bbp_moderator',
'capabilities' => array(),
),
);
//var_dump(serialize($postmeta));
/**
* @todo: make sure that $args[2] is actually a post and not an user or something
* @todo: Allow hierarchical permissions, so that we can assign a permission to a forum and carry it over to topics and replies
*
* @param array $allcaps Current user's capabilities
* @param array $caps Capabilities being tested against
* @param array $args Additional arguments passed to has_cap. Key [1] always contains the user ID
* @return array
*/
function poc_user_has_cap ( $allcaps, $caps, $args) {
global $post, $wp_roles;
if ( empty( $args[2] ) && is_null( $post ) )
return $allcaps;
$check_post = empty( $args[2] ) ? $post : get_post( $args[2] );
if ( empty( $check_post ) ) {
return $allcaps;
}
$postmeta = get_post_meta($check_post->ID, '_post_capabilities');
if ( empty( $postmeta ) || empty( $postmeta[0][$args[1]] ) ) {
return $allcaps;
}
$usercaps = $postmeta[0][$args[1]];
$allcaps = array_merge( $allcaps, !empty( $usercaps['capabilities'] ) ? $usercaps['capabilities'] : array() );
if ( !empty( $usercaps['role'] ) ) {
$role = $wp_roles->get_role( $usercaps['role'] );
if ( empty( $role ) ) {
return $allcaps;
}
$allcaps = array_merge( $allcaps, $role->capabilities );
}
return $allcaps;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment