Search This Blog

Tuesday, August 17, 2010

Add Settings/Options Page To Wordpress Theme


If you have developed a theme for wordpress and wondering if you could have a settings/options page, here is a quick tutorial. Having a custom theme settings page has its own advantage over hard-coding it. It avoids frequent edits to code, eases and simplifies operation, saves time and has lot many other benefits. Okay so lets move on.



The Logic :
Wordpress is a powerful framework that lets you add so many functionalities to your site. In this case we are concerned about what are called as 'hooks' that wordpress provides. Hooks are of 2 types Action and filter. As the name suggests action hooks are meant to perform some action on occurrence of some event while latter is used to modify the existing functions as per your convenience.

Here we make use of action hooks. I will be creating a settings page that will allow editing a custom content say a marquee somewhere on the page. To start with, we open the functions.php file, which is included on every page as long as your theme is active. Here we get a chance to define our starting or triggering point. We start off by registering our action hooks. We will use 3 hooks :
1)admin_menu : actions to be performed when admin enters the control panel or settings
2)switch_theme : actions to be performed when admin changes the theme
3)wp_head : actions to add something in the head section when header is requested.

Initialization :
Unfortunately there is no hook to define our initialization routine. So we use another method to detect theme change from previous theme to your theme. We analyze the parameters in the url for keyword 'activated' while on 'themes.php' page.
The code :



This code above will go into functions.php anywhere after the initial declarations. It will create a table in database called wp-prefix_mytheme_data where we can store our theme data. Manipulate the query based on your needs.

Registration :
We will use admin_menu hook to add our Theme Settings link to the sidebar.
The Code :



The above hook will call the add_to_menu function which will register the settings page defined in settings_form function.

In action :
We will use wp_head to add data(java scripts) to the head section.
The Code :



The above code will add jquery and jquery code to the head. In my theme i will have a div with id="marque-area", and the marquee with my data will be added within this div.

Unregister :
we will use switch_theme to destroy all the data after theme deactivation
The Code :



We have destroyed everything we had created as user no longer uses our theme.

Combine these codes into one contineous code and add it anywhere in functions.php file(Take care of php open and close tags)
Final Code :


No comments:

Post a Comment