Limit WordPress user to edit only his own pages - wordpress

I'm looking for the simplest way to limit a WordPress user to edit only his own pages (that is pages he is author of). I've read about some users manager plugins but for my needs they seems overkill and so I wonder if it is possible to obtain the same result adding some code lines to functions.php or something similar.

you can do this by adding a new role like so :
<?php add_role( $role, $display_name, $capabilities ); ?>
This setting is saved to the database (in table wp_options, field wp_user_roles), so it might be better to run this on theme/plugin activation
Returns a WP_Role object on success, null if that role already exists.
Example
Create a new "Basic Contributor" role.
$result = add_role(
'basic_contributor',
__( 'Basic Contributor' ),
array(
'read' => true, // true allows this capability
'edit_posts' => true,
'delete_posts' => false, // Use false to explicitly deny
)
);
if ( null !== $result ) {
echo 'Yay! New role created!';
}
else {
echo 'Oh... the basic_contributor role already exists.';
}
add_role() is located in wp-includes/capabilities.php.
for more clarification look in this article

Related

WordPress: User with custom role cannot access wp-admin

First of all I am a WordPress learner. So sorry if my code looks stupid!
I have created a custom theme with a custom user role. I am not developing any plugin.
In my fucntions.php file I have written the following code to create a User role. Users assigned to this role are supposed to login to the admin but only be able to access their Profile pages.
add_action('init', 'yrc_cst_register_role_customer_service_rep');
/**
* Register new user role
*/
function yrc_cst_register_role_customer_service_rep() {
$wp_roles = new WP_Roles();
$wp_roles->remove_role('subscriber');
$wp_roles->remove_role('editor');
$wp_roles->remove_role('contributor');
$wp_roles->remove_role('author');
$service_rep_caps = array(
'read' => false,
'create_posts' => false,
'edit_posts' => false,
'edit_others_posts' => false,
'publish_posts' => false,
'manage_categories' => false,
'manage_options' => false,
);
add_role('customer_service', __('Customer Service'), $service_rep_caps);
}
I have removed all roles except Administrator, because no other role is required for this portal. Administrator will only create Users with Customer Service role.
I have no third party plugin installed in the system.
Users with the custom role are able to login to the system through a custom login page which is working OK. But whenever they are trying to access their Profile page the following error message comes up:
Sorry, you are not allowed to access this page.
Is there anything like 'edit_profile' => true?
I must be doing something wrong but my limited knowledge is not enough to figure this out. Any suggestion would be highly appreciated.
You might be able to do it like this :
This should clone the subscriber role capabilities and create your role for it.
add_action('init', 'CreatecloneRoleSubscriber');
function CreatecloneRoleSubscriber()
{
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
$sub = $wp_roles->get_role('Subscriber');
//Adding a 'new_role' with all subscriber caps
$wp_roles->add_role('customer_service', 'Customer Service', $sub->capabilities);
}
EDIT : Read discussion in question comments
Just change the manage_options to true in your case
But note that by allowing manage_options to true, those user will have access to other parts of dashboard as well
$service_rep_caps = array(
'read' => false,
'create_posts' => false,
'edit_posts' => false,
'edit_others_posts' => false,
'publish_posts' => false,
'manage_categories' => false,
'manage_options' => true, // Most plugins and pages check for manage_options for checking access level to allow access to pages and settings.
);
Just found this solution which i consider really clean to enter wp-admin with a new role:
Add access cap to backend
Add the cap view_admin_dashboard & read to your new role.
Show the admin bar
Add this function to your wordpress.
# functions.php
add_filter( 'show_admin_bar', function () {
if ( current_user_can( 'view_admin_dashboard' ) )
return true;
return false;
}, 10);

Add Role to Registration in WP

I am looking for a way to add a dropdown for users in the registration form to select their role (except administrator).
Currently running wordpress 4.7.4 with buddypress 2.8.0., found some snippets and such but none of them are actually working.
Any help is much appreciated
You have to create user-role.php fileand include it in functions.php file.
<?php
if( get_role('subscriber') ){
remove_role( 'subscriber' );
}
if( get_role('client') ){
remove_role( 'client' );
}
// Add a Country (Others) role
$result = add_role( 'country', __(
'Country (Others)' ),
array(
'read' => true, // true allows this capability
'edit_posts' => true, // Allows user to edit their own posts
'edit_pages' => true, // Allows user to edit pages
'edit_others_posts' => true, // Allows user to edit others posts not just their own
'create_posts' => true, // Allows user to create new posts
'manage_categories' => true, // Allows user to manage post categories
'publish_posts' => true, // Allows the user to publish, otherwise posts stays in draft mode
'edit_themes' => false, // false denies this capability. User can’t edit your theme
'install_plugins' => false, // User cant add new plugins
'update_plugin' => false, // User can’t update any plugins
'update_core' => false // user cant perform core updates
)
);

WordPress add roles capabilities edit user

I want to add the capability of adding/eddeting/removing users to a new role.
However I can't find the right capabilities.
Any help please?
Current (from the WordPress Codex)
add_role('new-role', 'New Role', array(
'read' => true, // True allows that capability
'edit_posts' => false,
'delete_posts' => false, // Use false to explicitly deny
));
I would like to add something like: add_user, edit_user and remove_user
M.
-EDIT--EDIT--EDIT--EDIT--EDIT--EDIT-
I have made some progress.
This is what I have now:
add_role('new-role', 'New Role', array(
'read' => true, // True allows that capability
'edit_posts' => false,
'delete_posts' => false, // Use false to explicitly deny
'edit_users'=> true,
'level_10'=> true,
'delete_users' => true,
'create_users' => true,
'list_users'=>true,
'remove_users' > true,
'add_users' => true,
'promote_users'=> true
));
I can now add users but I can't edit users. The "user" tab doesn't show.
There is a "add new user" button under the "profile" menu.
M.
-EDIT--EDIT--EDIT--EDIT--EDIT--EDIT-
Okay I fixed it.
I was allready using the 'Adminimize' plugin so I duplicated the "Administrator"-role and hide everything that I didn't need:
function cloneRole()
{
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles();
$adm = $wp_roles->get_role('administrator');
//Adding a 'new_role' with all admin caps
$wp_roles->add_role('new_role', 'My Custom Role', $adm->capabilities);
}
Sadly, there is no ability within WordPress to set a role to be able to edit users. Reading through the WordPress source code, there is only the add and delete options for users but there are edit buttons for plugins, themes, posts, pages etc.
The actual code can be found here: WordPress Capabilities Trac
The lines it shows the user related roles are around line 1273 to 1288.
Sorry to disappoint.

Buddypress bp_activity_add(activity_action) hides the link "target"

I'm developing a social network with Buddypress, I created a RSS plugin to pull the RSS feed from the specified websites.
Everything is working, except when the RSS is posted to the activity stream. When I create the activity content to print a link, I set the link target to "_new" to open it in a new page.
Here's the code:
function wprss_add_to_activity_feed($item, $inserted_ID) {
$permalink = $item->get_permalink();
$title = $item->get_title();
$admin = get_user_by('login', 'admin');
# Generates the link
$activity_action = sprintf( __( '%s published a new RSS link: %s - ', 'buddypress'), bp_core_get_userlink( $admin->ID ), '' . attribute_escape( wprss_limit_rss_title_chars($title) ) . '');
/* Record this in activity streams */
bp_activity_add( array(
'user_id' => $admin->ID,
'item_id' => $inserted_ID,
'action' => $activity_action,
'component' => 'rss',
'primary_link' => $permalink,
'type' => 'activity_update',
'hide_sitewide' => false
));
}
It should come up with something like that:
Test
But it prints like that:
Test
Why is this happening?
The 'target' attribute is probably getting stripped by BuddyPress's implementation of the kses filters. You can whitelist the attribute as follows:
function se16329156_whitelist_target_in_activity_action( $allowedtags ) {
$allowedtags['a']['target'] = array();
return $allowedtags;
}
add_filter( 'bp_activity_allowed_tags', 'se16329156_whitelist_target_in_activity_action' );
This probably won't retroactively fix the issue for existing activity items - it's likely that they had the offending attribute stripped before being stored in the database. But it should help for future items.

WordPress: Disable "Add New" on Custom Post Type

Is there any way to disable the option of adding a new post under a Custom Post Type in WordPress (3.0)? I've looked into labels and arguments but can't find anything that would resemble such a feature.
There is a meta capability create_posts that is documented here and is used by WordPress to check before inserting the various 'Add New' buttons and links. In your custom post type declaration, add capabilities (not to be confused with cap) and then set it to false as below.
register_post_type( 'custom_post_type_name', array(
'capability_type' => 'post',
'capabilities' => array(
'create_posts' => false, // Removes support for the "Add New" function ( use 'do_not_allow' instead of false for multisite set ups )
),
'map_meta_cap' => true, // Set to `false`, if users are not allowed to edit/delete existing posts
));
You'll probably want to set map_meta_cap to true as well. Without it, you won't be able to access the posts' editing pages anymore.
The combinations of the solutions above work in hiding the links (although someone could quite easily type the URL in directly.
The solution mentioned #3pepe3 relies on get_post_type() which will only work if there is already a post in the listing. If there are no posts, the function will not return anything, and the "Add New" link will be available. An alternative method:
function disable_new_posts() {
// Hide sidebar link
global $submenu;
unset($submenu['edit.php?post_type=CUSTOM_POST_TYPE'][10]);
// Hide link on listing page
if (isset($_GET['post_type']) && $_GET['post_type'] == 'CUSTOM_POST_TYPE') {
echo '<style type="text/css">
#favorite-actions, .add-new-h2, .tablenav { display:none; }
</style>';
}
}
add_action('admin_menu', 'disable_new_posts');
EDIT: To prevent direct access if someone types the URL in themselves: https://wordpress.stackexchange.com/a/58292/6003
WordPress Networks: I found that Seamus Leahy's answer doesn't work if you are logged in as a super admin of the network, it doesn't matter if the user doesn't have the capability, mapped or otherwise, when current_user_can($cap) is called by the CMS. By digging into the core I found you can do the following.
register_post_type( 'custom_post_type_name', array(
'capability_type' => 'post',
'capabilities' => array(
'create_posts' => 'do_not_allow', // Removes support for the "Add New" function, including Super Admin's
),
'map_meta_cap' => true, // Set to false, if users are not allowed to edit/delete existing posts
));
The accepted answer hides the menu item, but the page is still accessible.
In wordpress and for all the post types there is the capability create_posts. This capability is used in several core files :
wp-admin\edit-form-advanced.php
wp-admin\edit.php
wp-admin\includes\post.php
wp-admin\menu.php
wp-admin\post-new.php
wp-admin\press-this.php
wp-includes\admin-bar.php
wp-includes\class-wp-xmlrpc-server.php
wp-includes\post.php
So if you really want to disable this feautere you must do it per role and per post type.
I use the great plugin "User Role Editor" to manage the capabilities per role.
But what about the capability create_posts? Well this capability is not mapped and also create_posts is equal to create_posts so we should fix this and map the capability per post type.
So you can add this piece of code in your functions.php and the you can manage this capability.
function fix_capability_create(){
$post_types = get_post_types( array(),'objects' );
foreach ( $post_types as $post_type ) {
$cap = "create_".$post_type->name;
$post_type->cap->create_posts = $cap;
map_meta_cap( $cap, 1);
}
}
add_action( 'init', 'fix_capability_create',100);
So here we are not hiding or removing menu elements... here we are removing the capability for users (including xmlrpc requests).
The action was init and not admin_init or anything else because init at priority 100 prevents the display of "add new" on admin bar, sidebar, etc (in all the wp interface).
Disable creating new post for registered post-types: (example for post and page)
function disable_create_newpost() {
global $wp_post_types;
$wp_post_types['post']->cap->create_posts = 'do_not_allow';
//$wp_post_types['page']->cap->create_posts = 'do_not_allow';
//$wp_post_types['my-post-type']->cap->create_posts = 'do_not_allow';
}
add_action('init','disable_create_newpost');
add_action("load-post-new.php", 'block_post');
function block_post()
{
if($_GET["post_type"] == "custom_type")
wp_redirect("edit.php?post_type=custom_type");
}
# Staffan Estberg,
This is best way to hide the Add New or Create New button in custom postypes
'capability_type' => 'post',
'capabilities' => array( 'create_posts' => false ),
'map_meta_cap' => true,
It disable to create new post in custom post types both side in admin menu and above the list of post type.
I found this simplest way for this. Just ad this code into theme’s function.php.
function hd_add_buttons() {
global $pagenow;
if (is_admin()) {
if ($_GET['post_type'] == 'custom_post_type_name') {
echo '<style>.add-new-h2{display: none !important;}</style>';
}
}
}
add_action('admin_head', 'hd_add_buttons');
As the question is 'how to disable add-new button on custom post type', and not 'how to restrict user editing custom post types', in my opinion the answer should be purely hiding the buttons with css, by adding this to the functions.php file :
add_action( 'admin_head', function(){
ob_start(); ?>
<style>
#wp-admin-bar-new-content{
display: none;
}
a.page-title-action{
display: none !important;
}
#menu-posts-MY-CUSTOM-POST-TYPE > ul > li:nth-child(3) > a{
display:none;
}
</style>
<?php ob_end_flush();
});

Resources