All WordPress snippets
Want your own copy?
Fork this repo and build your own snippet collection. Fork on GitHub →
WordPress
Build a Simple Custom Settings Page
Adds a new page under Appearance with the WordPress Settings API wired up — a starting point for a theme options panel with your own fields.
php
/**
* Create custom global settings
*/
function custom_settings_page() { ?>
<div class="wrap">
<h1>Custom Settings</h1>
<form method="post" action="options.php">
<?php
settings_fields( 'section' );
do_settings_sections( 'theme-options' );
submit_button();
?>
</form>
</div><?php
}
function custom_settings_add_menu() {
add_theme_page( 'Custom Settings', 'Custom Settings', 'manage_options', 'custom-settings', 'custom_settings_page', null, 99 );
}
add_action( 'admin_menu', 'custom_settings_add_menu' );
// Example setting
function setting_twitter() { ?>
<input type="text" name="twitter" id="twitter" value="<?php echo get_option('twitter'); ?>" /><?php
}
function custom_settings_page_setup() {
add_settings_section( 'section', 'All Settings', null, 'theme-options' );
add_settings_field( 'twitter', 'Twitter Username', 'setting_twitter', 'theme-options', 'section' );
register_setting( 'section', 'twitter' );
}
add_action( 'admin_init', 'custom_settings_page_setup' );
Reading the saved value
echo get_option( 'twitter' );
Adapted from Create a WordPress Theme Settings Page with the Settings API.
More WordPress snippets
Register and Output a Custom Nav Menu
Adds a new menu location you can assign in Appearance → Menus, shows how to output it in a template, and includes the multi-menu version too.
Define a Reusable Global String
A simple pattern for storing a value — like a phone number or address — in one place and reusing it anywhere in your theme.
Auto-Escape HTML Typed Inside Code Tags
Makes sure any markup typed inside <code> or <tt> tags in the editor gets escaped automatically, so it displays as visible text instead of being rendered as real HTML.