Dynamically Populating User Role

Use this snippet in conjunction with Gravity Forms dynamic population functionality to populate the current user’s role into any form field.

Read the Walkthrough

Code

Filename: gw-dynamically-populating-user-role.php

<?php
/**
 * Gravity Wiz // Gravity Forms // Dynamically Populating User Role
 * https://gravitywiz.com/dynamically-populating-user-role/
 *
 * Use this snippet in conjunction with Gravity Forms dynamic population
 * functionality to populate the current user’s role into any form field.
 *
 * @version  1.0
 * @author   David Smith <david@gravitywiz.com>
 * @license  GPL-2.0+
 * @link     https://gravitywiz.com/
 */
add_filter( 'gform_field_value_user_role', 'gform_populate_user_role' );
function gform_populate_user_role( $value ) {
	$user = wp_get_current_user();
	$role = $user->roles;
	return reset( $role );
}

Comments

  1. Matt Duncan
    Matt Duncan July 25, 2024 at 5:35 pm

    Does this work with GravityView (data tables)? When I edit the entry, it shows the original submitter’s role and not the current logged-in user’s role. I’m trying to figure out if I have a plugin conflict or if the functionality of it updating during edit is possible. I have a hidden field that I want to use conditional logic with based on the current logged-in user’s role.

    Reply
    1. Samuel Bassah
      Samuel Bassah Staff July 25, 2024 at 10:03 pm

      Hi Matt,

      Within GravityView, the field will show the value that is stored when the user initially submits the form, so what you’re experiencing is the expected behaviour. You’ll need to use a different solution, since you want to get the role of the currently logged-in user in GravityView. The new solution will require using GP Populate Anything Perk, to populate the field with the role of the currently logged-in user, and then use this snippet to force the field to rehydrate when editing the entry to get the role of the currently logged-in user.

      I hope this helps. However, if this isn’t still working for you, please contact us via our support form so we can have a closer look at your setup and assist you to get it working.

      Best,

Leave a Reply

Your email address will not be published. Required fields are marked *

  • Trouble installing this snippet? See our troubleshooting tips.
  • Need to include code? Create a gist and link to it in your comment.
  • Reporting a bug? Provide a URL where this issue can be recreated.

By commenting, I understand that I may receive emails related to Gravity Wiz and can unsubscribe at any time.