I am trying to create a custom field in 'settings > general' that I can then create a shortcode for to display on the front-end. I cannot find any particular code that will help specifically for this. Any suggestions would be highly appreciated.
Field label: Phone number
I am trying to create a custom field in 'settings > general' that I can then create a shortcode for to display on the front-end. I cannot find any particular code that will help specifically for this. Any suggestions would be highly appreciated.
Field label: Phone number
Share Improve this question asked Nov 12, 2020 at 9:47 nbowdskinbowdski 31 bronze badge1 Answer
Reset to default 1Please try this in your localhost:
- First, build the custom field in options-general.php aka General Settings page. (source)
/**
* Class for adding a new field to the options-general.php page
*/
class Add_Settings_Field {
/**
* Class constructor
*/
public function __construct() {
add_action( 'admin_init' , array( $this , 'register_fields' ) );
}
/**
* Add new fields to wp-admin/options-general.php page
*/
public function register_fields() {
register_setting( 'general', 'phone_number_custom', 'esc_attr' );
add_settings_field(
'custom_phone_number',
'<label for="custom_phone_number">' . __( 'Phone Number' , 'phone_number_custom' ) . '</label>',
array( $this, 'fields_html' ),
'general'
);
}
/**
* HTML for extra settings
*/
public function fields_html() {
$value = get_option( 'phone_number_custom', '' );
echo '<input type="text" id="custom_phone_number" name="phone_number_custom" value="' . esc_attr( $value ) . '" />';
}
}
new Add_Settings_Field();
You'll just need to adjust the label as per your needs. Screenshot of the result: https://prnt.sc/vhxenh
- Now, we need to build a shortcode to get the value:
add_shortcode( 'phone', function () {
$phonenumber = get_option( 'phone_number_custom', '' );
$out = '<span class="phone-styling">'.$phonenumber.'</span>';
return $out;
} );
This is the shortcode to call the value: [phone]
And this is how it looks like for the output: https://prnt.sc/vhxgtx
You'll just need to style it with a CSS class: .phone-styling
.
Hope it helps.