Menu

Create custom theme options page in WordPress

If you would like to have a custom theme options page in your WordPress theme, you can do it by simply adding below wp hooks.

below code goes in your functions.php

function theme_options_init(){
register_setting( 'extra_options', 'theme_extra_options');
}

function theme_options_add_page() {
add_theme_page( __( 'Theme Options', 'advancetheme' ), __( 'Theme Options', 'advancetheme' ), 'edit_theme_options', 'theme_options', 'theme_options_do_page' );
}

add the hooks to theme_setup in

add_action( 'admin_init', 'theme_options_init' );
add_action( 'admin_menu', 'theme_options_add_page' );

and you theme options page can be like this

<?php
if ( ! function_exists( 'theme_options_do_page' ) ):
function theme_options_do_page() 
{ 
	global $select_options; 
	if ( ! isset( $_REQUEST['settings-updated'] ) )
		$_REQUEST['settings-updated'] = false; 
?>

<div class="wrap">
  <?php screen_icon(); echo "<h2>". __( 'Custom Theme Options', 'customtheme' ) . "</h2>"; ?>
  <?php if ( false !== $_REQUEST['settings-updated'] ) : ?>
  <div class="updated settings-error" id="setting-error-settings_updated">
    <p><strong>
      <?php _e( 'Options saved', 'customtheme' ); ?>
      </strong></p>
  </div>
  <?php endif; ?>
  <form method="post" action="options.php">
    <?php settings_fields( 'extra_options' ); ?>
    <?php $options = get_option( 'theme_extra_options' ); ?>
    <table class="form-table">
      <tbody>
        <tr valign="top">
          <th scope="row"><?php _e( 'Facebook Profile', 'customtheme' ); ?></th>
          <td><input id="theme_extra_options[facebook_url]" 
                		name="theme_extra_options[facebook_url]" class="regular-text ltr" type="text" 
                        value="<?php esc_attr_e( $options['facebook_url'] ); ?>" ></td>
        </tr>
      </tbody>
    </table>
    <p class="submit">
      <input type="submit" value="<?php _e( 'Save Options', 'customtheme' ); ?>" class="button-primary" id="submit" name="submit">
    </p>
  </form>
</div>
<?php 
} 
endif;
?>

if you want to access your options in frontend templates, simply add this to header.php (all the way top)

<?php
$GLOBALS['custom'] = get_post_meta($post->ID);
$GLOBALS['options'] = $options = get_option( 'theme_extra_options' );
?>

to print particular property, do like below.

<?php echo $GLOBALS['options']['facebook_url']; ?>

Leave a comment