diff --git a/src/User.php b/src/User.php index b5abb1e88..76f67ef36 100644 --- a/src/User.php +++ b/src/User.php @@ -200,6 +200,18 @@ public function get_field($field_name = null) return $this->meta($field_name); } + /** + * Check if the user object is the current user + * + * @api + * + * @return bool true if the user is the current user + */ + public function is_current(): bool + { + return \get_current_user_id() === $this->ID; + } + /** * Get the name of the User * @@ -279,13 +291,13 @@ public function get_meta($field_name) } /** - * Creates an associative array with user role slugs and their translated names. - * - * @internal - * @since 1.8.5 - * @param array $roles user roles. - * @return array|null - */ + * Creates an associative array with user role slugs and their translated names. + * + * @internal + * @since 1.8.5 + * @param array $roles user roles. + * @return array|null + */ protected function get_roles($roles) { if (empty($roles)) { @@ -345,6 +357,32 @@ public function roles() return $this->roles; } + /** + * Gets the profile link to the user’s profile in the WordPress admin if the ID in the user object + * is the same as the current user’s ID. + * + * @api + * @since 2.1.0 + * @example + * + * Get the profile URL for the current user: + * + * ```twig + * {% if user.profile_link %} + * My profile + * {% endif %} + * ``` + * @return string|null The profile link for the current user. + */ + public function profile_link(): ?string + { + if (!$this->is_current()) { + return null; + } + + return \get_edit_profile_url($this->ID); + } + /** * Checks whether a user has a capability. * diff --git a/tests/test-timber-user.php b/tests/test-timber-user.php index 942ed0188..47063e4c9 100644 --- a/tests/test-timber-user.php +++ b/tests/test-timber-user.php @@ -195,6 +195,34 @@ public function testLinks() $this->assertEquals('16th', $user->president); } + public function testIsCurrent() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Charles vonderZwen', + 'user_login' => 'cvanderzwen', + ]); + + $user = Timber::get_user($uid); + + wp_set_current_user($uid); + + $this->assertTrue($user->is_current()); + } + + public function testProfileLink() + { + $uid = $this->factory->user->create([ + 'display_name' => 'Boaty McBoatface', + 'user_login' => 'BMcBoatface', + ]); + + wp_set_current_user($uid); + + $user = Timber::get_user($uid); + + $this->assertEquals('http://example.org/wp-admin/profile.php', $user->profile_link()); + } + public function testAvatar() { // Restore integration-free Class Map for users.