Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ipokkel/7c95d998b5ed8761894742e67a959a9a to your computer and use it in GitHub Desktop.
Save ipokkel/7c95d998b5ed8761894742e67a959a9a to your computer and use it in GitHub Desktop.
Set a placeholder for PMPro text, textarea, and number User Fields.
<?php
/**
* Set placeholder values for PMPro user fields.
*
* Supported field types: text, textarea, number.
*
* You can add this recipe to your site by creating a custom plugin
* or using the Code Snippets plugin available for free in the WordPress repository.
* Read this companion article for step-by-step directions on either method.
* https://www.paidmembershipspro.com/create-a-plugin-for-pmpro-customizations/
*/
function my_pmpro_user_fields_html_attributes_placeholder() {
global $pmpro_user_fields;
// Set placeholder values for the fields. Format: 'field_name' => 'placeholder value'
$placeholder = array(
'example_text' => 'Enter text here.',
'example_textarea' => 'Row one.' . "\r\n" . 'Row two.' . "\r\n" . 'Row three.',
'example_number' => '123',
);
// Loop through the fields and set the html_attributes array values.
foreach ( $pmpro_user_fields as $field_group => $fields ) {
foreach ( $fields as $field ) {
// Bail if field type is not supported.
if ( ! in_array( $field->type, array( 'text', 'textarea', 'number' ), true ) ) {
continue;
}
if ( isset( $placeholder[ $field->name ] ) ) {
// Bail if field value is set
if ( ! empty( $field->value ) ) {
continue;
}
// Bail if $placeholder is not a string.
if ( ! is_string( $placeholder[ $field->name ] ) ) {
continue;
}
// Remove html tags from string.
$placeholder[ $field->name ] = wp_strip_all_tags( $placeholder[ $field->name ] );
// remove all non-numbers from string if field type is number.
if ( 'number' === $field->type ) {
$placeholder[ $field->name ] = preg_replace( '/[^0-9]/', '', $placeholder[ $field->name ] );
}
// Set placeholder value for html_attributes if it's not already set.
if ( empty( $field->html_attributes['placeholder'] ) ) {
$field->html_attributes['placeholder'] = esc_attr( $placeholder[ $field->name ] );
}
}
}
}
}
add_action( 'init', 'my_pmpro_user_fields_html_attributes_placeholder' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment