How to create shortcodes that pull custom field data from general settings

Please try this in your localhost:

  1. 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

  1. 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.

Leave a Comment