Make WordPress Core


Ignore:
Timestamp:
11/02/2016 12:30:29 AM (9 years ago)
Author:
pento
Message:

Roles/Capabilities: Add a new wp_roles_init filter.

Historically, it's been difficult to extend user roles, but reasonable to work around by waiting until after init has fired, to add custom roles and capabilities. With the addition of Locale Switching, Core now potentially loads roles before init has fired, leaving a window where custom roles and capabilities are not handled.

The new filter allows plugins to add their own custom roles whenever they're initialised (on page load, or when switching sites, for example), so that they can always be obeyed.

WP_Roles has also been tidied up a little bit, to remove duplicate code.

Props johnjamesjacoby, pento.
Fixes #23016.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/user/capabilities.php

    r39035 r39082  
    4242        unset($GLOBALS['wp_user_roles']);
    4343        global $wp_roles;
    44         if ( is_object( $wp_roles ) )
    45             $wp_roles->_init();
     44        $wp_roles = new WP_Roles();
    4645    }
    4746
     
    16271626    }
    16281627
     1628    protected $_role_test_wp_roles_role;
     1629    /**
     1630     * @ticket 23016
     1631     */
     1632    public function test_wp_roles_init_action() {
     1633        $this->_role_test_wp_roles_init = array(
     1634            'role' => 'test_wp_roles_init',
     1635            'info' => array(
     1636                'name' => 'Test WP Roles Init',
     1637                'capabilities' => array( 'testing_magic' => true ),
     1638            ),
     1639        );
     1640        add_action( 'wp_roles_init', array( $this, '_hook_wp_roles_init' ), 10, 1 );
     1641
     1642        $wp_roles = new WP_Roles();
     1643
     1644        remove_action( 'wp_roles_init', array( $this, '_hook_wp_roles_init' ) );
     1645
     1646        $expected = new WP_Role( $this->_role_test_wp_roles_init['role'], $this->_role_test_wp_roles_init['info']['capabilities'] );
     1647
     1648        $role = $wp_roles->get_role( $this->_role_test_wp_roles_init['role'] );
     1649
     1650        $this->assertEquals( $expected, $role );
     1651        $this->assertContains( $this->_role_test_wp_roles_init['info']['name'], $wp_roles->role_names );
     1652    }
     1653
     1654    public function _hook_wp_roles_init( $wp_roles ) {
     1655        $wp_roles->add_role( $this->_role_test_wp_roles_init['role'], $this->_role_test_wp_roles_init['info']['name'], $this->_role_test_wp_roles_init['info']['capabilities'] );
     1656    }
    16291657}
Note: See TracChangeset for help on using the changeset viewer.