SlideShare a Scribd company logo
Create a Settings Page For Your
WordPress Theme
Junejo Naeem Ahmed
WORDPRESS
WORDPRESS THEME
• Creating your own theme for WordPress is a great way to give
your blog or other WordPress powered web site an original
touch.
• But even the nicest looking theme is not that nice if you have
to get under the hood and edit the theme's HTML or PHP
code whenever it's time change some aspects of it.
• Especially, when it's not you but a paying customer using your
theme.
• Luckily, creating a settings page for your theme in WordPress
is not very hard!
DECIDING WHAT SETTINGS ARE NEEDED
• It all starts from the need: to create a clear and useful settings page,
you have to figure out the things that will need to be changed and
leave out everything else.
• Every new setting you add to the admin menus adds complexity to the
user interface and risks making the theme harder to use.
• That's why it's better to be careful and handpick the options that are
going to be changed often and leave out one time customizations that
can easily be done changing one file inside the theme.
• Another question to keep in mind is "Who is going to be changing
these settings?“
• If the user is familiar with PHP and WordPress, it might be reasonable
to expect that he is OK with embedding his Google Analytics code in
the code herself.
• but you shouldn't require that from a graphic designer, not to mention
a writer who doesn't even need to know anything about HTML and
CSS.
DECIDING WHAT SETTINGS ARE NEEDED
• Common ideas for things to define in theme settings include:
• The site's Google Analytics tracking code
• The number of sidebars and their positioning (left, right, maybe even
up and down)
• Page width
• The contents of your footer
• Options for features that are specific to the theme, such as custom
teaser formats.
DECIDING WHAT SETTINGS ARE NEEDED
• Once you have collected the list of theme features that you'd like to
control through a settings page, you are almost ready to start the
implementation.
• Before you move on and create your settings page, you can save time
by making sure that there isn't a WordPress feature already available
for the customization you have in mind.
• Widgets, custom menus, custom backgrounds and header images are
all useful tools for making your theme customizable with a lot less
work than required for creating your own settings.
HOOKING THE SETTINGS PAGE TO WORDPRESS
• Creating a settings page starts by creating a function that sets up the
menu and hooking it to the WordPress action admin_menu.
• This tells WordPress to call your function when its time to create the
menus so that everything is done at its proper time.
• Add this code to your theme's functions.php file:
• function setup_theme_admin_menus() {
• // We will write the function contents very soon.
• }
• // This tells WordPress to call the function named
"setup_theme_admin_menus"
• // when it's time to create the menu pages.
• add_action("admin_menu", "setup_theme_admin_menus");
HOOKING THE SETTINGS PAGE TO WORDPRESS
• We'll now put the code for creating the settings pages inside the
function we just created.
• When creating your settings page, you have the choice of either adding
the page as a submenu to one of the existing settings groups or of
creating your own top level menu.
• Adding a submenu is done with the function add_submenu_page:
• <?php add_submenu_page($parent_slug, $page_title,
$menu_title, $capability, $menu_slug, $function) ?>
HOOKING THE SETTINGS PAGE TO WORDPRESS
• $parent_slug is a unique identifier for the top menu page to which this
submenu is added as a child.
• $page_title is the title of the page to be added
• $menu_title is the title shown in the menu (often a shorter version of
$page_title
• $capability is the minimum capability required from a user in order to
have access to this menu.
• $menu_slug is a unique identifier for the menu being created
• $function is the name of a function that is called to handle (and
render) this menu page.
HOOKING THE SETTINGS PAGE TO WORDPRESS
• If you choose to add the menu page as a submenu to one of the
WordPress groups, you can use the following values as the
$parent_slug parameter:
• Dashboard: index.php
• Posts: edit.php
• Media: upload.php
• Links: link-manager.php
• Pages: edit.php?post_type=page
• Comments: edit-comments.php
• Appearance: themes.php
• Plugins: plugins.php
• Users: users.php
• Tools: tools.php
• Settings: options-general.php
HOOKING THE SETTINGS PAGE TO WORDPRESS
• The Appearance group looks like a good candidate for placing our
settings page.
• Let's try that, and create our first settings page.
• Here's an updated version of our menu setup function:
• function setup_theme_admin_menus() {
• add_submenu_page('themes.php',
• 'Front Page Elements', 'Front Page', 'manage_options',
• 'front-page-elements', 'theme_front_page_settings');
• }
• We still need to create the function theme_front_page_settings for
this to work. Here it is in its simplest form:
• function theme_front_page_settings() {
• echo "Hello, world!";
• }
HOOKING THE SETTINGS PAGE TO WORDPRESS
HOOKING THE SETTINGS PAGE TO WORDPRESS
• We also need to check that the user has the rights required for editing
the settings page.
• To do that, add the following code at the beginning of the settings
page function:
• // Check that the user is allowed to update options
• if (!current_user_can('manage_options')) {
• wp_die('You do not have sufficient permissions to access this page.');
• }
• Now, if a user who isn't allowed to manage options comes to the
settings page, he will see nothing but the message, "You do not have
sufficient permissions to access this page."
HOOKING THE SETTINGS PAGE TO WORDPRESS
• If your theme needs multiple settings pages, it can be confusing for the
user to look for them scattered all around the menu structure.
• In that case, creating your own settings group makes it easier for the
theme user to find all the menu pages for the theme.
• To add your own settings group, you need to create a top level menu
page and link the submenu pages to it.
• Here is a new version of our menu setup function.
• The add_menu_page function used to create the top level menu is
similar to add_submenu_page except that it doesn't take the
$parent_slug parameter.
HOOKING THE SETTINGS PAGE TO WORDPRESS
• function setup_theme_admin_menus() {
• add_menu_page('Theme settings', 'Example theme', 'manage_options',
• ‘my_theme_settings', 'theme_settings_page');
•
• add_submenu_page(‘my_theme_settings',
• 'Front Page Elements', 'Front Page', 'manage_options',
• 'front-page-elements', 'theme_front_page_settings');
• }
•
• // We also need to add the handler function for the top level menu
• function theme_settings_page() {
• echo "Settings page";
• }
HOOKING THE SETTINGS PAGE TO WORDPRESS
• If you test the code and refresh the WordPress admin, you'll see your
new menu group appear at the bottom of the menu list:
HOOKING THE SETTINGS PAGE TO WORDPRESS
• But something doesn't look quite right yet.
• Clicking the top menu element doesn't lead you to the "Front Page"
menu but a menu page called "Example theme.“
• This is not consistent with how the other WordPress menus function,
so let's do one more thing: by changing the $menu_slug attribute in
the add_submenu_page call to the same value as in the top level
menu, we can link the two menus so that selecting the top menu
selects the front page menu:
function setup_theme_admin_menus() {
add_menu_page('Theme settings', 'Example theme', 'manage_options',
‘my_theme_settings', 'theme_settings_page');
add_submenu_page(‘my_theme_settings',
'Front Page Elements', 'Front Page', 'manage_options',
‘my_theme_settings', 'theme_front_page_settings');
}
function theme_settings_page() {
}
HOOKING THE SETTINGS PAGE TO WORDPRESS
• Looks better. If you want to still improve the looks of your menu group,
there are two optional fields in the add_menu_page function that you
will find useful.
• Just add the values after the function name in the method call:
• $icon_url specifies the URL of an icon for the top level menu.
• $position specifies the position of your menu group in the menu list.
• The higher the value, the lower the position in the menu.
CREATING THE HTML FORM FOR THE SETTINGS PAGES
• Now that we have created the settings page, and it shows up
nicely in the side menu, it's time to start adding some
content.
• So, let's go back to the list of settings we had in mind, and
draft a page for editing them.
• we need a field for defining how many elements should be
listed on one row, and a list for defining the actual elements.
• To start from the easier, let's create a text field for the number
of elements on one row.
CREATING THE HTML FORM FOR THE SETTINGS PAGES
• Edit your settings page function:
• function theme_front_page_settings() {
• ?>
• <label for="num_elements">
• Number of elements on a row:
• </label>
•
• <input type="text" name="num_elements" />
• <?php
• }
CREATING THE HTML FORM FOR THE SETTINGS PAGES
• When you reload your settings page, you'll see the first settings field
appear:
CREATING THE HTML FORM FOR THE SETTINGS PAGES
• To make the settings page fit seamlessly in the WordPress experience and to give your
theme a professional touch, it's a best practice to use the CSS classes and styles that
WordPress uses in its own settings pages.
• A good way to learn the tricks is to just go ahead and analyze the WordPress source
code.
• The most important thing is to wrap your setting page with a div with the class "wrap".
• Within that div element, you can use many predefined styles such as headings, buttons,
and form fields.
• Let's start by styling the title of our settings page:
• We will create a h2 heading for the page (You can use the heading tags from h2 to h6 to
create headings with different sizes.)
• We will show the theme settings page icon before the heading. (You can use the
predefined WordPress icons with the screen_icon function.
• The function can take one of the following parameters: index, edit, upload, link-
manager, pages, comments, themes, plugins, users, tools or options-general.)
• We will put the input element inside a form and a table with the class form-table.
CREATING THE HTML FORM FOR THE SETTINGS PAGES
• function theme_front_page_settings() {
• ?>
• <div class="wrap">
• <?php screen_icon('themes'); ?> <h2>Front page elements</h2>
•
• <form method="POST" action="">
• <table class="form-table">
• <tr valign="top">
• <th scope="row">
• <label for="num_elements">
• Number of elements on a row:
• </label>
• </th>
• <td>
• <input type="text" name="num_elements" size="25" />
• </td>
• </tr>
• </table>
• </form>
• </div>
• <?php
• }
CREATING THE HTML FORM FOR THE SETTINGS PAGES
SAVING THE FORM
• The settings page looks good, but there is something missing: it doesn't do
anything yet.
• It's time to save some data.
• WordPress provides an easy system for saving theme and plugin settings
as key value pairs to the database using two functions:
• get_option and update_option.
• The data stored using the functions can be as simple as a number value or
as complex as an array nested multiple times.
• The handling of the form is done in the same function that renders the
form.
• To know whether a form was submitted or not, we add a hidden field,
update_settings to the form and then check whether that field was sent or
not in the handling function.
SAVING THE FORM
• if (isset($_POST["update_settings"])) {
• // Do the saving
• }
• The hidden field that goes inside the form looks like this:
• <input type="hidden" name="update_settings" value="Y" />
SAVING THE FORM
• Let's start by saving the easier setting, num_elements.
• We'll escape the attribute to make sure the user isn't sending malicious
content in the from of HTML tags and then save it to the WordPress
settings storage.
• When using update_option, we don't need to worry about whether the
setting has already been saved or not.
• $num_elements = esc_attr($_POST["num_elements"]);
• update_option("theme_name_num_elements", $num_elements);
SAVING THE FORM
• Before we move to saving the list, let's add the current value of
num_elements to the settings form so that the user always sees what
value he has entered in before deciding the next value.
• This will also help us test that the value was actually saved.
• <input type="text" name="num_elements" value="<?php echo
$num_elements;?>" size="25" />
• And for cases where we haven't saved anything yet, we'll need to load the
current value from options, so let's add this piece of code to be executed
when there is no form submitted.
• $num_elements = get_option("theme_name_num_elements");
SAVING THE FORM
• When a form is saved, it's important to notify the user so that he isn't left
wondering whether something happened or not.
• So, let's render a simple notice saying "Settings saved." right after the
update_option:
• <div id="message" class="updated">Settings saved</div>
USING THE SETTINGS INSIDE THE THEME
• Saving and showing settings values within the admin area is great, but
what really counts is how you use them to customize your theme, so now,
we have come to the point where it's time to take our settings and do
something cool with them.
• From here on, changes go to index.php instead of functions.php. First,
we'll read the options to variables:
• <?php
• $num_elements = get_option("theme_name_num_elements");
• ?>
CONCLUSION
• Now, we have created a settings page for a custom theme.
• The theme is far from complete, but I hope this introduction got you
started with adding settings and customizable elements to your next
WordPress theme.

More Related Content

What's hot (20)

PPTX
Webiny CMS Starter Guide
Webiny
 
PPT
Easy Guide to WordPress Theme Integration
Sankhala Info Solutions
 
KEY
Plugin Options
WordCamp New Zealand
 
KEY
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
cehwitham
 
PPTX
WordPress theme development from scratch : ICT MeetUp 2013 Nepal
Chandra Prakash Thapa
 
PPTX
Custom WordPress theme development
Tammy Hart
 
PPTX
WordPress HTML, CSS & Child Themes
Michelle Ames
 
PDF
Dreamweaver cs6 step by step
zoran Jelinek
 
PPTX
WordPress Structure and Best Practices
markparolisi
 
PDF
How to Prepare a WordPress Theme for Public Release
David Yeiser
 
PDF
Intro to WordPress Child Themes (NERDS Sept 2014)
Kelly Dwan
 
PPTX
WordPress Theme Development: Part 2
Josh Lee
 
PPTX
Moving from Wordpress.com to Wordpress.org - Wordcamp Toronto 2011
Georgiana Laudi
 
PDF
Content-Driven WordPress Development - WordCamp Omaha 2014
Stephanie Eckles
 
PDF
WordPress Theme Structure
keithdevon
 
PPTX
Childthemes ottawa-word camp-1919
Paul Bearne
 
PPTX
Day of code
Evan Farr
 
PDF
Theme Wrangling 101
mikeyarce
 
PPTX
Rebrand WordPress Admin
Chandra Prakash Thapa
 
PDF
WordPress Theme Development for Designers
elliotjaystocks
 
Webiny CMS Starter Guide
Webiny
 
Easy Guide to WordPress Theme Integration
Sankhala Info Solutions
 
Plugin Options
WordCamp New Zealand
 
Making WordPress Your CMS and Automatically Updating a Self Hosted WordPress ...
cehwitham
 
WordPress theme development from scratch : ICT MeetUp 2013 Nepal
Chandra Prakash Thapa
 
Custom WordPress theme development
Tammy Hart
 
WordPress HTML, CSS & Child Themes
Michelle Ames
 
Dreamweaver cs6 step by step
zoran Jelinek
 
WordPress Structure and Best Practices
markparolisi
 
How to Prepare a WordPress Theme for Public Release
David Yeiser
 
Intro to WordPress Child Themes (NERDS Sept 2014)
Kelly Dwan
 
WordPress Theme Development: Part 2
Josh Lee
 
Moving from Wordpress.com to Wordpress.org - Wordcamp Toronto 2011
Georgiana Laudi
 
Content-Driven WordPress Development - WordCamp Omaha 2014
Stephanie Eckles
 
WordPress Theme Structure
keithdevon
 
Childthemes ottawa-word camp-1919
Paul Bearne
 
Day of code
Evan Farr
 
Theme Wrangling 101
mikeyarce
 
Rebrand WordPress Admin
Chandra Prakash Thapa
 
WordPress Theme Development for Designers
elliotjaystocks
 

Similar to WordPress theme setting page (20)

PDF
After Wordpress Website Installation, Now What?
Abbie De Villar
 
PDF
Wordpress chapter1
Arifa Orfan
 
PDF
Using Wordpress with Reclaim Hosting
Cindy Royal
 
PPTX
NamesCon 2015 Wordpress Beginner Session
Bruce Marler
 
PDF
WordPress customizer: for themes and more
R-Cubed Design Forge
 
PDF
Making WordPress Your Own: Theme Customization & Creation
Mykl Roventine
 
PPTX
The Way to Theme Enlightenment 2017
Amanda Giles
 
PPTX
How to content manage everything
Interconnect IT
 
PDF
Creating Customizer Options for Themes and Plugins
R-Cubed Design Forge
 
PPTX
The Way to Theme Enlightenment
Amanda Giles
 
PPTX
Theme customization
Merrill Mayer
 
PDF
Developing for the WordPress Customizer
Anthony Hortin
 
PDF
Wordpress Guide
Sunanda Bansal
 
PDF
Developing For The WordPress Customizer
Anthony Hortin
 
PPTX
Customizing WordPress Themes
Domestic Equity Studio
 
PPTX
Wordpress tutorial
Santosh Verma
 
PPTX
Wordpress workflow for an agency world
Chris Lowe
 
PPTX
Basic word press development
David Wolfpaw
 
PDF
WordPress Theme Workshop: Theme Setup
David Bisset
 
PDF
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
LinnAlexandra
 
After Wordpress Website Installation, Now What?
Abbie De Villar
 
Wordpress chapter1
Arifa Orfan
 
Using Wordpress with Reclaim Hosting
Cindy Royal
 
NamesCon 2015 Wordpress Beginner Session
Bruce Marler
 
WordPress customizer: for themes and more
R-Cubed Design Forge
 
Making WordPress Your Own: Theme Customization & Creation
Mykl Roventine
 
The Way to Theme Enlightenment 2017
Amanda Giles
 
How to content manage everything
Interconnect IT
 
Creating Customizer Options for Themes and Plugins
R-Cubed Design Forge
 
The Way to Theme Enlightenment
Amanda Giles
 
Theme customization
Merrill Mayer
 
Developing for the WordPress Customizer
Anthony Hortin
 
Wordpress Guide
Sunanda Bansal
 
Developing For The WordPress Customizer
Anthony Hortin
 
Customizing WordPress Themes
Domestic Equity Studio
 
Wordpress tutorial
Santosh Verma
 
Wordpress workflow for an agency world
Chris Lowe
 
Basic word press development
David Wolfpaw
 
WordPress Theme Workshop: Theme Setup
David Bisset
 
Don't Fear the Custom Theme: How to build a custom WordPress theme with only ...
LinnAlexandra
 
Ad

More from Naeem Junejo (6)

PPTX
Freelancing
Naeem Junejo
 
PPTX
Introduction databases and MYSQL
Naeem Junejo
 
PPTX
Introduction To WordPress
Naeem Junejo
 
PPTX
jQuery Mobile
Naeem Junejo
 
PPTX
Wordpress custom-posttype
Naeem Junejo
 
PPTX
Wordpress theme development
Naeem Junejo
 
Freelancing
Naeem Junejo
 
Introduction databases and MYSQL
Naeem Junejo
 
Introduction To WordPress
Naeem Junejo
 
jQuery Mobile
Naeem Junejo
 
Wordpress custom-posttype
Naeem Junejo
 
Wordpress theme development
Naeem Junejo
 
Ad

Recently uploaded (20)

PDF
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PPT
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
PPTX
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
PPTX
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
PDF
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
PDF
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
PDF
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
PPTX
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
PDF
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
PDF
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PDF
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
PPTX
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
PPTX
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 
DIGESTION OF CARBOHYDRATES,PROTEINS,LIPIDS
raviralanaresh2
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
Talk on Critical Theory, Part II, Philosophy of Social Sciences
Soraj Hongladarom
 
I AM MALALA The Girl Who Stood Up for Education and was Shot by the Taliban...
Beena E S
 
SPINA BIFIDA: NURSING MANAGEMENT .pptx
PRADEEP ABOTHU
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 - GLOBAL SUCCESS - CẢ NĂM - NĂM 2024 (VOCABULARY, ...
Nguyen Thanh Tu Collection
 
Knee Extensor Mechanism Injuries - Orthopedic Radiologic Imaging
Sean M. Fox
 
The Constitution Review Committee (CRC) has released an updated schedule for ...
nservice241
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
How to Handle Salesperson Commision in Odoo 18 Sales
Celine George
 
How to Create a PDF Report in Odoo 18 - Odoo Slides
Celine George
 
LAW OF CONTRACT (5 YEAR LLB & UNITARY LLB )- MODULE - 1.& 2 - LEARN THROUGH P...
APARNA T SHAIL KUMAR
 
The-Ever-Evolving-World-of-Science (1).pdf/7TH CLASS CURIOSITY /1ST CHAPTER/B...
Sandeep Swamy
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
0725.WHITEPAPER-UNIQUEWAYSOFPROTOTYPINGANDUXNOW.pdf
Thomas GIRARD, MA, CDP
 
Neurodivergent Friendly Schools - Slides from training session
Pooky Knightsmith
 
How to Manage Large Scrollbar in Odoo 18 POS
Celine George
 

WordPress theme setting page

  • 1. Create a Settings Page For Your WordPress Theme Junejo Naeem Ahmed WORDPRESS
  • 2. WORDPRESS THEME • Creating your own theme for WordPress is a great way to give your blog or other WordPress powered web site an original touch. • But even the nicest looking theme is not that nice if you have to get under the hood and edit the theme's HTML or PHP code whenever it's time change some aspects of it. • Especially, when it's not you but a paying customer using your theme. • Luckily, creating a settings page for your theme in WordPress is not very hard!
  • 3. DECIDING WHAT SETTINGS ARE NEEDED • It all starts from the need: to create a clear and useful settings page, you have to figure out the things that will need to be changed and leave out everything else. • Every new setting you add to the admin menus adds complexity to the user interface and risks making the theme harder to use. • That's why it's better to be careful and handpick the options that are going to be changed often and leave out one time customizations that can easily be done changing one file inside the theme. • Another question to keep in mind is "Who is going to be changing these settings?“ • If the user is familiar with PHP and WordPress, it might be reasonable to expect that he is OK with embedding his Google Analytics code in the code herself. • but you shouldn't require that from a graphic designer, not to mention a writer who doesn't even need to know anything about HTML and CSS.
  • 4. DECIDING WHAT SETTINGS ARE NEEDED • Common ideas for things to define in theme settings include: • The site's Google Analytics tracking code • The number of sidebars and their positioning (left, right, maybe even up and down) • Page width • The contents of your footer • Options for features that are specific to the theme, such as custom teaser formats.
  • 5. DECIDING WHAT SETTINGS ARE NEEDED • Once you have collected the list of theme features that you'd like to control through a settings page, you are almost ready to start the implementation. • Before you move on and create your settings page, you can save time by making sure that there isn't a WordPress feature already available for the customization you have in mind. • Widgets, custom menus, custom backgrounds and header images are all useful tools for making your theme customizable with a lot less work than required for creating your own settings.
  • 6. HOOKING THE SETTINGS PAGE TO WORDPRESS • Creating a settings page starts by creating a function that sets up the menu and hooking it to the WordPress action admin_menu. • This tells WordPress to call your function when its time to create the menus so that everything is done at its proper time. • Add this code to your theme's functions.php file: • function setup_theme_admin_menus() { • // We will write the function contents very soon. • } • // This tells WordPress to call the function named "setup_theme_admin_menus" • // when it's time to create the menu pages. • add_action("admin_menu", "setup_theme_admin_menus");
  • 7. HOOKING THE SETTINGS PAGE TO WORDPRESS • We'll now put the code for creating the settings pages inside the function we just created. • When creating your settings page, you have the choice of either adding the page as a submenu to one of the existing settings groups or of creating your own top level menu. • Adding a submenu is done with the function add_submenu_page: • <?php add_submenu_page($parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function) ?>
  • 8. HOOKING THE SETTINGS PAGE TO WORDPRESS • $parent_slug is a unique identifier for the top menu page to which this submenu is added as a child. • $page_title is the title of the page to be added • $menu_title is the title shown in the menu (often a shorter version of $page_title • $capability is the minimum capability required from a user in order to have access to this menu. • $menu_slug is a unique identifier for the menu being created • $function is the name of a function that is called to handle (and render) this menu page.
  • 9. HOOKING THE SETTINGS PAGE TO WORDPRESS • If you choose to add the menu page as a submenu to one of the WordPress groups, you can use the following values as the $parent_slug parameter: • Dashboard: index.php • Posts: edit.php • Media: upload.php • Links: link-manager.php • Pages: edit.php?post_type=page • Comments: edit-comments.php • Appearance: themes.php • Plugins: plugins.php • Users: users.php • Tools: tools.php • Settings: options-general.php
  • 10. HOOKING THE SETTINGS PAGE TO WORDPRESS • The Appearance group looks like a good candidate for placing our settings page. • Let's try that, and create our first settings page. • Here's an updated version of our menu setup function: • function setup_theme_admin_menus() { • add_submenu_page('themes.php', • 'Front Page Elements', 'Front Page', 'manage_options', • 'front-page-elements', 'theme_front_page_settings'); • } • We still need to create the function theme_front_page_settings for this to work. Here it is in its simplest form: • function theme_front_page_settings() { • echo "Hello, world!"; • }
  • 11. HOOKING THE SETTINGS PAGE TO WORDPRESS
  • 12. HOOKING THE SETTINGS PAGE TO WORDPRESS • We also need to check that the user has the rights required for editing the settings page. • To do that, add the following code at the beginning of the settings page function: • // Check that the user is allowed to update options • if (!current_user_can('manage_options')) { • wp_die('You do not have sufficient permissions to access this page.'); • } • Now, if a user who isn't allowed to manage options comes to the settings page, he will see nothing but the message, "You do not have sufficient permissions to access this page."
  • 13. HOOKING THE SETTINGS PAGE TO WORDPRESS • If your theme needs multiple settings pages, it can be confusing for the user to look for them scattered all around the menu structure. • In that case, creating your own settings group makes it easier for the theme user to find all the menu pages for the theme. • To add your own settings group, you need to create a top level menu page and link the submenu pages to it. • Here is a new version of our menu setup function. • The add_menu_page function used to create the top level menu is similar to add_submenu_page except that it doesn't take the $parent_slug parameter.
  • 14. HOOKING THE SETTINGS PAGE TO WORDPRESS • function setup_theme_admin_menus() { • add_menu_page('Theme settings', 'Example theme', 'manage_options', • ‘my_theme_settings', 'theme_settings_page'); • • add_submenu_page(‘my_theme_settings', • 'Front Page Elements', 'Front Page', 'manage_options', • 'front-page-elements', 'theme_front_page_settings'); • } • • // We also need to add the handler function for the top level menu • function theme_settings_page() { • echo "Settings page"; • }
  • 15. HOOKING THE SETTINGS PAGE TO WORDPRESS • If you test the code and refresh the WordPress admin, you'll see your new menu group appear at the bottom of the menu list:
  • 16. HOOKING THE SETTINGS PAGE TO WORDPRESS • But something doesn't look quite right yet. • Clicking the top menu element doesn't lead you to the "Front Page" menu but a menu page called "Example theme.“ • This is not consistent with how the other WordPress menus function, so let's do one more thing: by changing the $menu_slug attribute in the add_submenu_page call to the same value as in the top level menu, we can link the two menus so that selecting the top menu selects the front page menu: function setup_theme_admin_menus() { add_menu_page('Theme settings', 'Example theme', 'manage_options', ‘my_theme_settings', 'theme_settings_page'); add_submenu_page(‘my_theme_settings', 'Front Page Elements', 'Front Page', 'manage_options', ‘my_theme_settings', 'theme_front_page_settings'); } function theme_settings_page() { }
  • 17. HOOKING THE SETTINGS PAGE TO WORDPRESS • Looks better. If you want to still improve the looks of your menu group, there are two optional fields in the add_menu_page function that you will find useful. • Just add the values after the function name in the method call: • $icon_url specifies the URL of an icon for the top level menu. • $position specifies the position of your menu group in the menu list. • The higher the value, the lower the position in the menu.
  • 18. CREATING THE HTML FORM FOR THE SETTINGS PAGES • Now that we have created the settings page, and it shows up nicely in the side menu, it's time to start adding some content. • So, let's go back to the list of settings we had in mind, and draft a page for editing them. • we need a field for defining how many elements should be listed on one row, and a list for defining the actual elements. • To start from the easier, let's create a text field for the number of elements on one row.
  • 19. CREATING THE HTML FORM FOR THE SETTINGS PAGES • Edit your settings page function: • function theme_front_page_settings() { • ?> • <label for="num_elements"> • Number of elements on a row: • </label> • • <input type="text" name="num_elements" /> • <?php • }
  • 20. CREATING THE HTML FORM FOR THE SETTINGS PAGES • When you reload your settings page, you'll see the first settings field appear:
  • 21. CREATING THE HTML FORM FOR THE SETTINGS PAGES • To make the settings page fit seamlessly in the WordPress experience and to give your theme a professional touch, it's a best practice to use the CSS classes and styles that WordPress uses in its own settings pages. • A good way to learn the tricks is to just go ahead and analyze the WordPress source code. • The most important thing is to wrap your setting page with a div with the class "wrap". • Within that div element, you can use many predefined styles such as headings, buttons, and form fields. • Let's start by styling the title of our settings page: • We will create a h2 heading for the page (You can use the heading tags from h2 to h6 to create headings with different sizes.) • We will show the theme settings page icon before the heading. (You can use the predefined WordPress icons with the screen_icon function. • The function can take one of the following parameters: index, edit, upload, link- manager, pages, comments, themes, plugins, users, tools or options-general.) • We will put the input element inside a form and a table with the class form-table.
  • 22. CREATING THE HTML FORM FOR THE SETTINGS PAGES • function theme_front_page_settings() { • ?> • <div class="wrap"> • <?php screen_icon('themes'); ?> <h2>Front page elements</h2> • • <form method="POST" action=""> • <table class="form-table"> • <tr valign="top"> • <th scope="row"> • <label for="num_elements"> • Number of elements on a row: • </label> • </th> • <td> • <input type="text" name="num_elements" size="25" /> • </td> • </tr> • </table> • </form> • </div> • <?php • }
  • 23. CREATING THE HTML FORM FOR THE SETTINGS PAGES
  • 24. SAVING THE FORM • The settings page looks good, but there is something missing: it doesn't do anything yet. • It's time to save some data. • WordPress provides an easy system for saving theme and plugin settings as key value pairs to the database using two functions: • get_option and update_option. • The data stored using the functions can be as simple as a number value or as complex as an array nested multiple times. • The handling of the form is done in the same function that renders the form. • To know whether a form was submitted or not, we add a hidden field, update_settings to the form and then check whether that field was sent or not in the handling function.
  • 25. SAVING THE FORM • if (isset($_POST["update_settings"])) { • // Do the saving • } • The hidden field that goes inside the form looks like this: • <input type="hidden" name="update_settings" value="Y" />
  • 26. SAVING THE FORM • Let's start by saving the easier setting, num_elements. • We'll escape the attribute to make sure the user isn't sending malicious content in the from of HTML tags and then save it to the WordPress settings storage. • When using update_option, we don't need to worry about whether the setting has already been saved or not. • $num_elements = esc_attr($_POST["num_elements"]); • update_option("theme_name_num_elements", $num_elements);
  • 27. SAVING THE FORM • Before we move to saving the list, let's add the current value of num_elements to the settings form so that the user always sees what value he has entered in before deciding the next value. • This will also help us test that the value was actually saved. • <input type="text" name="num_elements" value="<?php echo $num_elements;?>" size="25" /> • And for cases where we haven't saved anything yet, we'll need to load the current value from options, so let's add this piece of code to be executed when there is no form submitted. • $num_elements = get_option("theme_name_num_elements");
  • 28. SAVING THE FORM • When a form is saved, it's important to notify the user so that he isn't left wondering whether something happened or not. • So, let's render a simple notice saying "Settings saved." right after the update_option: • <div id="message" class="updated">Settings saved</div>
  • 29. USING THE SETTINGS INSIDE THE THEME • Saving and showing settings values within the admin area is great, but what really counts is how you use them to customize your theme, so now, we have come to the point where it's time to take our settings and do something cool with them. • From here on, changes go to index.php instead of functions.php. First, we'll read the options to variables: • <?php • $num_elements = get_option("theme_name_num_elements"); • ?>
  • 30. CONCLUSION • Now, we have created a settings page for a custom theme. • The theme is far from complete, but I hope this introduction got you started with adding settings and customizable elements to your next WordPress theme.