英文:
How to add capabilities to WP_Role when it cannot be converted to string
问题
我在尝试向两个用户角色添加新功能时收到了这个错误:
错误:在第67行无法将WP_Role类的对象转换为字符串...
我尝试添加的功能将允许用户查看我们在WP设置中构建的自定义页面。这是我编写的用于填充角色的代码:
public static function add_csv_capability():void {
$rolesToPopulate = array((get_role( 'administrator' )), (get_role( 'editor' )));
$roles = array_fill_keys(($rolesToPopulate),NULL);
echo $roles;
foreach ($roles as $role) {
if ($role) {
$role->add_cap('use_csv_uploader');
}
}
}
有人问过这里是否能回答我的问题,答案既是又不是。它解释了错误的原因,但既然我知道错误的原因,我现在需要弄清楚如何让这段代码做我想要的事情,即允许我向多个角色添加功能。
如果你能提供任何帮助,将不胜感激。
谢谢!
英文:
I am receiving this error when trying to add new capabilities to two of my user roles:
Error: Object of class WP_Role could not be converted to string ... on line 67
The capability I am trying to add will allow the user to see a custom page that we have built in our WP setup. This is the code I have written to populate the roles:
public static function add_csv_capability():void {
$rolesToPopulate = array((get_role( 'administrator' )), (get_role( 'editor' )));
$roles = array_fill_keys(($rolesToPopulate),NULL);
echo $roles;
foreach ($roles as $role) {
if ($role) {
$role->add_cap('use_csv_uploader');
}
}
}
Someone asked if this would answer my question, and it does and it doesn't. It explains what the error is, but now that I know what the error is all about, I need to figure out how to get this code to do what I want, which is to allow me to add capabilities to more than one role.
Any help you can give would be greatly appreciated.
Thanks!
答案1
得分: 0
首先,创建一个角色名称数组,然后使用array_fill_keys()
函数创建一个关联数组,其中这些角色名称作为键,值为null。然后,您可以循环遍历该数组,使用get_role()
函数检索相应的WP_Role
对象,然后将能力添加到该角色中。
因此,您可以使用角色名称的数组而不是WP_Role
对象的数组,如下所示:
public static function add_csv_capability(): void {
$rolesToPopulate = array('administrator', 'editor');
$roles = array_fill_keys($rolesToPopulate, NULL);
foreach ($roles as $role) {
if ($role) {
$role_obj = get_role($role);
$role_obj->add_cap('use_csv_uploader');
}
}
}
希望这有助于解决您面临的问题。
英文:
First, create an array of role names and then use array_fill_keys() to create an associative array with these role names as keys and null as values. You then loop through this array and retrieve the corresponding WP_Role object using get_role() and then add the capability to that role.
So you can use an array of role names instead of an array of WP_Role objects, like this
public static function add_csv_capability():void {
$rolesToPopulate = array('administrator', 'editor');
$roles = array_fill_keys($rolesToPopulate, NULL);
foreach ($roles as $role) {
if ($role) {
$role_obj = get_role($role);
$role_obj->add_cap('use_csv_uploader');
}
}
}
I hope this helps you fix the issue you are facing.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论