Skip to content

Instantly share code, notes, and snippets.

@hamidrezayazdani
Last active January 9, 2021 17:58
Show Gist options
  • Save hamidrezayazdani/8b863f88ae3e2e9e872188bdbdcf074e to your computer and use it in GitHub Desktop.
Save hamidrezayazdani/8b863f88ae3e2e9e872188bdbdcf074e to your computer and use it in GitHub Desktop.
Show User meta as default value in GravityForm
<?php
/**
* GravityForm default user's merge tags doc: https://docs.gravityforms.com/user-merge-tag/
* Sometimes, default merge tags are not enough for us.
* With this snippet you can add custom user meta as a
* new merge tag to gform.
*/
/**
* Add gravity form custom merge tag
*/
add_filter( 'gform_custom_merge_tags', 'ywp_add_custom_merge_tag', 10, 4 );
function ywp_add_custom_merge_tag( $merge_tags, $form_id, $fields, $element_id ) {
$merge_tags[] = array(
'label' => 'User Phone',
'tag' => '{user_phone}',
);
return $merge_tags;
}
/**
* replace CMT with real data
*/
add_filter( 'gform_replace_merge_tags', 'ywp_replace_merge_tags', 10, 7 );
function ywp_replace_merge_tags( $text, $form, $lead, $url_encode, $esc_html, $nl2br, $format ) {
$userid = get_current_user_id();
$phone = $userid ? get_user_meta( $userid, 'phone', true ) : ''; //replace 'phone' with mihan panel user phone that saved in 'wp_usermeta'
$text = str_replace( '{user_phone}', $phone, $text );
return $text;
}
/**
* show CTM in from fields
*/
add_filter( 'gform_field_content', 'ywp_field_content', 10, 5 );
function ywp_field_content( $field_content, $field, $value, $lead_id, $form_id ) {
if ( strpos( $field_content, '{user_phone}') !== false ) {
$userid = get_current_user_id();
$phone = $userid ? get_user_meta( $userid, 'phone', true ) : '';
$field_content = str_replace( '{user_phone}', $phone, $field_content );
}
return $field_content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment