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

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x