diff --git a/docs/usage/wordpress.md b/docs/usage/wordpress.md index e9d65a0..8ecb454 100644 --- a/docs/usage/wordpress.md +++ b/docs/usage/wordpress.md @@ -409,7 +409,7 @@ Accessing an ACF field, sub field, or even option field is just as easy: ## @role -`@role` is a simple conditional that allows you to display specific content only to users who are logged in and have a specific role. With [`wp_get_current_user()->roles`](https://developer.wordpress.org/reference/functions/wp_get_current_user/) returning an array of roles in all lowercase, the passed role is automatically lowercased using `strtolower`. It can be closed using `@endrole`. +`@role` allows you to display specific content only to users who are logged in and have a specific role. With [`wp_get_current_user()->roles`](https://developer.wordpress.org/reference/functions/wp_get_current_user/) returning an array of roles in all lowercase, the passed role is automatically lowercased using `strtolower`. It can be closed using `@endrole`. ```php @role('author') @@ -417,6 +417,12 @@ Accessing an ACF field, sub field, or even option field is just as easy: @endrole ``` +```php +@role('author', 'contributor') + This content is only displayed to Authors and Contributors. +@endrole +``` + ## @user `@user` is a simple `is_user_logged_in()` conditional to display specific content only when a user is logged in. It can be closed using `@enduser`. diff --git a/src/Directives/WordPress.php b/src/Directives/WordPress.php index 7d0a1de..b350412 100644 --- a/src/Directives/WordPress.php +++ b/src/Directives/WordPress.php @@ -431,8 +431,15 @@ 'role' => function ($expression) { $expression = Util::parse($expression); + $condition = []; - return "get(0)}), (array) wp_get_current_user()->roles)) : ?>"; // phpcs:ignore + foreach ($expression as $value) { + $condition[] = "&& in_array(strtolower({$value}), (array) wp_get_current_user()->roles)"; + } + + $conditions = implode(' ', $condition); + + return ""; // phpcs:ignore }, 'endrole' => function () { diff --git a/tests/Unit/WordPressTest.php b/tests/Unit/WordPressTest.php index ab67eb4..994955f 100644 --- a/tests/Unit/WordPressTest.php +++ b/tests/Unit/WordPressTest.php @@ -554,6 +554,14 @@ expect($compiled)->toBe("roles)) : ?>"); }); + + it('compiles correctly with multiple roles', function () { + $directive = "@role('editor', 'author', 'contributor')"; + + $compiled = $this->compile($directive); + + expect($compiled)->toBe("roles) && in_array(strtolower('author'), (array) wp_get_current_user()->roles) && in_array(strtolower('contributor'), (array) wp_get_current_user()->roles)) : ?>"); + }); }); describe('@endrole', function () {