wordpress logo

How to add an option to WordPress general settings

wordpress logo

How to add an option to wordpress general settings page i.e. /wp-admin/options-general.php?

how-to-add-a-checkbox-option-to-wordpress-general-settings - add an option to wordpress general settings

The dirty way. Put the following snippet in functions.php file:

add_filter( 'admin_init' , 'clinto_register_fields' );
function clinto_register_fields() {
	//delete_option( "clinto_under_maintenance" );
	register_setting( 'general', 'clinto_under_maintenance', 'esc_attr' );
	add_settings_field('mk_clinto_under_maintenance', '<label for="clinto_under_maintenance">'. 'Under Maintenance' . '</label>' , 'clinto_fields_html' , 'general' );
}
function clinto_fields_html() {
	$value = get_option( 'clinto_under_maintenance');
	$checked = ($value=='yes') ? 'checked="checked"' : '';
	echo '<input type="hidden" name="clinto_under_maintenance" value="no" /><input id="clinto_under_maintenance" type="checkbox" checked="checked" name="clinto_under_maintenance" value="yes" />';
}

Recommended way, so that you keep everything grouped and out of conflict troubles. Put the following snippet in functions.php file:

Create a class with required logic and then create an instance.

class clinto_general_settings {
    function clinto_general_settings() {
        add_filter( 'admin_init' , array( &$this , 'clinto_register_fields' ) );
    }
    function clinto_register_fields() {
        register_setting( 'general', 'clinto_under_maintenance', 'esc_attr' );
        add_settings_field('mk_clinto_under_maintenance', '<label for="clinto_under_maintenance">'.__('Under Maintenance' , 'clinto_under_maintenance' ).'</label>' , array(&$this, 'clinto_fields_html') , 'general' );
    }
    function clinto_fields_html() {
        $value = get_option( 'clinto_under_maintenance');
		$checked = ($value=='yes') ? 'checked="checked"' : '';
        echo '<input type="hidden" name="clinto_under_maintenance" value="no" /><input id="clinto_under_maintenance" type="checkbox" checked="checked" name="clinto_under_maintenance" value="yes" />';
    }
}

$clinto_general_settings = new clinto_general_settings();

Whenever you wanted to check the value of option you will obviously do:

$value = get_option( 'clinto_under_maintenance');

Leave a Reply

Your email address will not be published. Required fields are marked *