Skip to content

Instantly share code, notes, and snippets.

@ipokkel
Last active November 7, 2022 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ipokkel/29aecf7b35f368b9cdda81057e268ab5 to your computer and use it in GitHub Desktop.
Save ipokkel/29aecf7b35f368b9cdda81057e268ab5 to your computer and use it in GitHub Desktop.
Custom User Field save_function callback example that will capitalize input string value.
<?php
// Create a registration form field with a custom callback
function my_pmpro_user_field_example_save_function() {
// Don't break if PMPro is out of date or not loaded.
if ( ! function_exists( 'pmpro_add_user_field' ) ) {
return false;
}
// define the fields
$fields = array();
// Basic Text Field Example
$fields[] = new PMPro_Field(
'pet_name', // input field name, used as meta key
'text', // field type
array(
'label' => 'Pet Name', // field label
'profile' => true, // display on user profile
'save_function' => 'my_capitalize_registration_field_value', // use a custom callback function
)
);
foreach ( $fields as $field ) {
pmpro_add_user_field(
'checkout_boxes', // location on checkout page
$field // PMPro_Field object
);
}
}
add_action( 'init', 'my_pmpro_user_field_example_save_function' );
// Custom callback function to capitalize string value
function my_capitalize_registration_field_value( $user_id, $field_name, $field_value ) {
// Do nothing if no value or if not string
if ( empty( $field_value ) || ! is_string( $field_value ) ) {
return;
}
// Captilize words
$field_value = ucwords( $field_value );
// Sanitize before saving to the database.
$field_value = sanitize_text_field( $field_value );
// Save to the usermeta table
update_user_meta( $user_id, $field_name, $field_value );
}
@laurenhagan0306
Copy link

This recipe is included in the blog post on "How to Use a Custom Callback Function For User Profile or Registration Fields" at Paid Memberships Pro here: https://www.paidmembershipspro.com/custom-callback-function-save-user-registration-profile-fields/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment