Quickly Add Custom Settings to WordPress admin General Settings

This is a template to quickly add two custom settings to the WordPress admin General Settings. With this, your custom settings can be set and saved in the WP Settings page, and you can then use get_option() to use your custom settings throughout your PHP files.

These settings will be text input fields.

Note that this is a template. While it does work as is, you may want to change the option names and titles on lines 6 and 7.

PHP

/**
 * Add 2 custom settings (text inputs) to WordPress admin Settings > General Settings
 */
function rec_register_settings() {
    $settings = array(
    	'my_option_name' => 'Title For This Option',
    	'my_other_option_name' => 'Title For This Other Option'
    );
    foreach ($settings as $id => $title) {
	    register_setting(
	        'general',
	        $id,
	        array('sanitize_callback' => 'sanitize_text_field', 'show_in_rest' => false)
	    );
	    add_settings_field(
	        $id,
	        $title,
	        'myoptions_text_field',
	        'general',
	        'default',
	        array('label_for' => $id)
	    );
	}
}
function myoptions_text_field($arg) {
    printf(
        '<input type="text" class="regular-text" name="%1$s" value="%2$s" id="%1$s" />',
        esc_attr( $arg['label_for'] ),
        esc_attr(get_option($arg['label_for'], ''))
    );
}
// only on admin side
add_action('admin_init', 'rec_register_settings');

Use The Options

Use these settings/options like you would any other WordPress option, using get_option().

To get the value of the first option:

$value = get_option( 'my_option_name' );

To get the value of the second option:

$other_value = get_option( 'my_other_option_name' );

Note that if you changed the my_option_name and my_other_option_name in the top function, then you must use those same new names here for the get_option() argument.

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]