問題描述
我有大量的使用者與編輯 Capabilities 幫助透過提交的帖子。這是我目前為此角色設定的:
您可以看到,它們被允許使用 edit_posts 和 edit_others_posts,但它們不能 edit_published_posts 。這意味著他們可以編輯處於草稿和待處理狀態的帖子。
現在,我想限制他們只能編輯待處理的帖子。所以,他們將無法觸及起草稿 (除非是作者的作者) 。不幸的是沒有能力像 edit_pending_posts … 應該有。
我該如何解決?
最佳解決方法
這實際上並不困難要新增新功能,請呼叫 WP_Roles->add_cap()。你只需要這樣做一次,因為它將被儲存在資料庫中。所以我們使用一個外掛啟用鉤子。
其他讀者注意:所有以下程式碼均為 plugin territory 。
register_activation_hook( __FILE__, 'epp_add_cap' );
/**
* Add new capability to "editor" role.
*
* @wp-hook "activate_" . __FILE__
* @return void
*/
function epp_add_cap()
{
global $wp_roles;
if ( ! isset( $wp_roles ) )
$wp_roles = new WP_Roles;
$wp_roles->add_cap( 'editor', 'edit_pending_posts' );
}
現在我們必須過濾所有的呼叫…
current_user_can( $post_type_object->cap->edit_post, $post->ID );
因為這是 WordPress 如何檢查使用者是否可以編輯帖子。在內部,這將被對映到其他作者帖子的 edit_others_posts 功能。
因此,當有些人想使用 edit_post 功能時,我們必須過濾 user_has_cap 並檢視我們的新的 edit_pending_posts 功能。
我也包括 delete_post,因為這也是一種編輯。
聽起來很複雜,但真的很簡單:
add_filter( 'user_has_cap', 'epp_filter_cap', 10, 3 );
/**
* Allow editing others pending posts only with "edit_pending_posts" capability.
* Administrators can still edit those posts.
*
* @wp-hook user_has_cap
* @param array $allcaps All the capabilities of the user
* @param array $caps [0] Required capability ('edit_others_posts')
* @param array $args [0] Requested capability
* [1] User ID
* [2] Post ID
* @return array
*/
function epp_filter_cap( $allcaps, $caps, $args )
{
// Not our capability
if ( ( 'edit_post' !== $args[0] && 'delete_post' !== $args[0] )
or empty ( $allcaps['edit_pending_posts'] )
)
return $allcaps;
$post = get_post( $args[2] );
// Let users edit their own posts
if ( (int) $args[1] === (int) $post->post_author
and in_array(
$post->post_status,
array ( 'draft', 'pending', 'auto-draft' )
)
)
{
$allcaps[ $caps[0] ] = TRUE;
}
elseif ( 'pending' !== $post->post_status )
{ // Not our post status
$allcaps[ $caps[0] ] = FALSE;
}
return $allcaps;
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
