Occasionally, I’ll run into a situation where I need to call a post specifically using the get_post() function. get_post() returns a Post object, with a number of member variables – the one that stores the actual content of the post being post_content.
However, if you try just echoing $post->post_content, you’ll get completely unformatted text – which is frustrating, because WordPress uses a great visual text editor on the backend – it’s a shame to not take advantage of it. Fortunately, WordPress provides a filter to display the text just as it would be displayed in the the_content() function inside the loop. Here’s how it works:
To get the content formatted properly, we need to apply a filter (which is different from adding a filter – here, we’re registering it so that other filter functions can modify it before it’s displayed).
apply_filters('the_content', $post->post_content);
So, we’re just applying the the_content filter to the $post->post_content variable. Doing so means that any plugin which adds a filter function to the_content like this:
add_filter('the_content', 'my_content_manipulator');
function my_content_manipulator($content){
//do stuff here
return $content;
}
will be applied to your variable. Fortunately, it also means that the WordPress core functions which format the post content correctly can also work on it.
Need more info about the $post object? Check out this post: .
Here’s something that comes up for me pretty often: depending on what I’m trying to do, I sometimes need plugin functions to run (or not run) simply based on which admin page the user is visiting. Here’s the WordPress function that will give you the title of the currently loaded admin page:
get_admin_page_title()
So, if you only want to run a bit of code on the “Edit Posts” page, you’d put together a conditional statement like this:
if(get_admin_page_title() == 'Edit Posts'){
//do something fancy
}
Post meta is easily one of the most useful features in WordPress from a developer’s perspective. Adding custom content to a post provides the ability to accomplish countless goals quickly and easily.
Sometimes, it makes sense to give the user access to a post meta field – for example, if they need to add a thumbnail url to a post, they’re probably going to need to access to those post meta fields. Other times, having the post meta field visible is only likely to confuse the visitor. One (extremely popular) place that I’ve seen this is the All in One SEO Plugin. All in One SEO is wildly popular, and does what it claims well. It provides a few extra fields, and a nice, easy to use interface to get at them. Here’s what it looks like when you get started:
Fantastic. It’s attractive, easy to use, and works well. So we save our post, and then later on, we go back to edit the meta description. Here’s what we get:
At this point, its pretty clear what’s going on if you understand the inner workings of WordPress – AIOSEO has saved our values to custom fields, so now they’re showing up there. However, most users dont understand, or even care about how AIOSEO works, or what custom fields are. All they know is that strange stuff is showing up, and they’re not sure where to edit their meta keywords, because they’re showing up in 2 places. Most people have the gumption to just change one and see what happens – but there will always be users who get scared and decide they want to email you about the issue, or worse, just uninstall the plugin and move on.
The WordPress developers, fortunately, thought of this. In fact, they store all kinds of stuff that they don’t want the user to see in custom fields – things like the last time the post was edited, who is currently editing it, and a few others. A quick look at the database, reveals this:
Notice a trend? The mysterious custom field key values are prepended with an underscore. Give it a try – enter a new custom field from the edit-post page, and enter a name that starts with an underscore – like _thumbnail, or _meta_keywords. Hit “Add Custom Field”, and it disappears – but if you check the database, its right where it should be.
Now get out there and start hiding things from your users!
Here’s a very cool little tidbit I found today (strangely enough, I found it in the bbpress codebase, while working on a bbpress plugin..) WordPress keeps track of which function/filter combinations are registered, along with which action hooks have been called at any point. If you’re having trouble trying to figure out which action hook you should use to run some code for your plugin or theme, give this a try (on a test install, of course).
As far as I can tell, this holds every currently registered function/filter combination, and all the relevant information. I can’t quite figure out exactly what determines which filters this grabs – I’ve tried calling it from a few places, and the results are slightly different, but I can’t seem to find a pattern. I initially assumed that you wouldnt be able to see about admin side hooks from the front end, but this isn’t the case. At any rate, you get lots of information from anywhere. Not getting the info you want? Call it from somewhere else! This is a great debugging tool if you’re having trouble with plugin incompatibility – it gives you a list of the filters and actions being called,the matching functions that are working on them, the priority specified for each hook call, the accepted args, and even the order in which same-priority-level hooks are called. An example:
[the_title] => Array
(
[10] => Array
(
[wptexturize] => Array
(
[function] => wptexturize
[accepted_args] => 1
)
[convert_chars] => Array
(
[function] => convert_chars
[accepted_args] => 1
)
[trim] => Array
(
[function] => trim
[accepted_args] => 1
)
)
)
This is a small snippet I pulled after displaying the contents of this variable in the footer of a theme. As you can see, the referenced hook is a filter, specifically “the_title”. It has 3 functions attached to it: wptexturize, convert_chars, and trim. Each one is at priority level 10 (which is the default), but they are called in the order listed. Each accepts 1 argument.
If you want to have a look yourself, display the contents of wp_filter with this code snippet:
<?php global $wp_filter; print_r($wp_filter); ?>
This is going to dump the contents right to the screen, so you don’t want to do it on a live blog. As with any use of the print_r() function, the results will be formatted nicely in the source code – but not in the rendered html.
This isn’t a terribly difficult task – it’s incredibly common, and it’s covered multiple places in the codex. So why am I writing about it? A few months ago, I was tasked with customizing a plugin – one that someone else wrote. I need to add some options to it, and their code was baffling to me. I could see that they were using custom options, but I couldnt understand how they were being set – it was like the author just made some form fields and hoped for the best.
What was happening is referenced here (Right in the codex – apparently the last place I thought to look). My first instinct has always been to post forms on an admin page to itself, then handle checking for the $_POST values, and creating/updating the appropriate options. As is often the case, WordPress makes it even easier than that:
I wont get into the boring details – you can look at the codex page for that – but pay special attention to the hidden fields you set up:
<input name="action" type="hidden" value="update" /> <input name="page_options" type="hidden" value="new_option_name,some_other_option,option_etc" />
Not too tough to understand – the first line tells the system that we’re going to be updating, and the second line lets WordPress know which fields we want to create/update. These, of course, need to match the “name” attribute of the input elements up above.
I posted a few days ago about the very cool functionality of maybe_serialize(), and its relation to WordPress options. I often store arrays in options, because they help keep the database free of unnecessary clutter, and they make your plugin even easier to use (from a developers view). I was a little worried that this “page options” trick would prevent me from saving arrays – but alas, WordPress saved the day again:
<input type="text" name="fruit_colors['apple']" value="red"> <input type="text" name="fruit_colors['carrot']" value="orange"> <input type="text" name="fruit_colors['banana']" value="yellow">
Just make a form field an array, like you would with a set of checkboxes (by adding [] after it). Pass in the proper values to the page_option hidden field, like so:
<input name="page_options" type="hidden" value="fruit_colors" />
This can get pretty interesting – a few days ago I used to to loop through categories and associate a string with each one – you can do the same for posts, days of the week, whatever suits your plugin.
So there you go. You’ve got yourself an option without any tinkering with $_POST variables, or checking if you need to update or create an option. WordPress even takes care of serializing it for you. What a world…
Ralph over at ForTheLose.org wrote up a great post on how to use custom fields in wordpress a few days ago, and I thought I’d expand on it with another feature that I use for clients quite often. Custom fields are a great way to store extra post information, and they can really make for some more interesting layouts.
Sometimes, however, they can be a little much for a non-tech savvy client or user to handle – they’ve got to choose the right custom field from the dropdown, or type it in properly, or it won’t work – and what if you’ve got a few specific option values you’d like them to choose from for the custom field? Sometimes it’s just too risky to expect the user to be able to handle it.
With this in mind, I started looking into how to modify the Add Post and Edit Post pages (ok, they’re really the same page). As it turns out, its not too terribly difficult to add in a few options of your own on the post page, giving the user attractive, easy to use access to more advanced features of your theme or plugin. A few examples:
This one was a fun project for me – I had a client who wanted to have a different sidebar on his “testimonials” page (he was a consultant). Now, I started to just set up a new post template for him, but I realized that he really wasnt going to want to call me every time he wanted to add a new testimonial – that would be ridiculous. I had really helped sell him on the idea of using wordpress so he wouldn’t need to call me a few times a month to make small changes to his website – so forcing him to do so to change his testimonials wouldnt be acceptable.
After giving that some thought, I decided to make another widgetized sidebar for use with the testimonials page template. This way, he could add text widgets to just that sidebar. I got to work, and got it set up, and decided that wasn’t quite right either – what if down the road he decided he wanted to show those testimonials on a sales page, or some other page I hadn’t thought of? He’d be out of luck. I decided what I really wanted to do was set up a number of sidebars (I ended up with 6), and allow him to choose the sidebars (it was a 3 column theme) for each page. Custom Fields were the perfect fit for the job, but that meant he’d have to remember the name of each of the sidebars when he wanted to change them. A custom post options box seemed just the right fit. And it did – he was really excited about the functionality, and I was excited to have learned something new.
Another project tasked me with creating a wordpress theme site for a client. He wanted each theme post to have a number of fields relating to its layout and structure – things like number of columns, if it was widgetized, etc. I decided that the easy way would be to just put the info into the post body, maybe in some custom tags or something – but wouldn’t it be cool if users could search by this info? I got to work. What I ended up with was a custom post options box with all the relevant theme info – dropdowns and checkboxes, which removed any possibility of error from user input. The client was happy, and as always, I had a good time doing it.
Before we get to how to actually implement this, a word of warning: with great power comes great responsibility. In this case, you’ve got great power to annoy your users – if you’re releasing a plugin with minor functionality that probably doesnt need a decision made on a per-post basis, it’s probably best to leave it off of the post page. There is no sense in cluttering and slowing down the post page if it isn’t completely necessary.
The actual implementation of this isn’t too hairy – we’ve basically got 4 parts:
First things first – we’ve got to reserve a spot on the oh-so-exclusive edit post page. Here’s how we do it:
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
add_meta_box('post_info', 'Post Information', 'custom_post_info', 'post', 'side', 'high');
}
First things first – we hook into the admin_menu action, with our callback function my_post_options_box(). With this callback function, we initiate the actual box – with the add_meta_box() call. Add meta box works like this:
add_meta_box(‘id’, ‘title’, ‘callback’, ‘page’, ‘context’, ‘priority’)
Now we’re going to actually display the options on the page:
function custom_post_info() {
global $post;
?>
<fieldset id="mycustom-div">
<div>
<p>
<label for="cpi_dropdown_options" >Dropdown Options:</label><br />
<select name="cpi_dropdown_options" id="cpi_dropdown_options">
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 1' ); ?>>Option 1</option>
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 2' ); ?>>Option 2</option>
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 3' ); ?>>Option 3</option>
</select>
<br />
<br />
<label for="cpi_text_option">Text Option:</label><br />
<input type="text" name="cpi_text_option" id="cpi_text_option" value="<?php echo get_post_meta($post->ID, 'cpi_text_option', true); ?>">
</p>
</div>
</fieldset>
<?php
}
Nothing too fancy going on here – but a couple of important points – we grab the $post global at the top – we do this so we can check against already stored values in the database (for editing posts instead of creating them). The entire section is wrapped in a fieldset, a div, and a paragraph – this ensures that the display matchces the rest of the boxes. Other than that, its a pretty standard form, we’ve got a dropdown menu and a text box waiting to be populated.
We’ve had the user set the options, all that is left is to retrieve them on “Save Draft” or “Publish”, and put them where they really belong – in custom fields. This is a little trickier than I expected it to be (and maybe I’ve made it too difficult. If somebody can think of a way to simplify this, please let me know).
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
// called after a post or page is saved
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['cpi_dropdown_options']) {
update_custom_meta($postID, $_POST['cpi_dropdown_options'], 'cpi_dropdown_options');
}
if ($_POST['cpi_text_option']) {
update_custom_meta($postID, $_POST['cpi_text_option'], 'cpi_text_option');
}
}
The first thing we do is hook into the save_post action. This is called on both saving and publishing, so we should be covered. Our custom_add_save takes a post id as input from the save_post action, and we need it to tell wordpress where to save our options.
Next, we need to figure out if the post id we got matches a real post, or just a revision. Revisions are stored in the database right alongside posts, with their own id and all – so we use the wp_is_post_revision function to determine if we’re working with a revision. If we are, wp_is_post_revision conveniently hands off the id of the parent post for us to use.
Now we’ll check to see if our options were posted. If we find a $_POST option matching one of our fields, we use that to update the custom field relating to it – but since we have to do this a few times, I’ve sent the actual work of updating the custom fields to another function – update_custom_meta(). Here, we check if the post_meta (custom field) is already set – if it is, we just update it. If it isn’t, we add a new one.
// ===================
// = POST OPTION BOX =
// ===================
add_action('admin_menu', 'my_post_options_box');
function my_post_options_box() {
add_meta_box('post_info', 'Post Information', 'custom_post_info', 'post', 'side', 'high');
}
//Adds the actual option box
function custom_post_info() {
global $post;
?>
<fieldset id="mycustom-div">
<div>
<p>
<label for="cpi_dropdown_options" >Dropdown Options:</label><br />
<select name="cpi_dropdown_options" id="cpi_dropdown_options">
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 1' ); ?>>Option 1</option>
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 2' ); ?>>Option 2</option>
<option<?php selected( get_post_meta($post->ID, 'cpi_dropdown_options', true), 'Option 3' ); ?>>Option 3</option>
</select>
<br />
<br />
<label for="cpi_text_option">Text Option:</label><br />
<input type="text" name="cpi_text_option" id="cpi_text_option" value="<?php echo get_post_meta($post->ID, 'cpi_text_option', true); ?>">
</p>
</div>
</fieldset>
<?php
}
add_action('save_post', 'custom_add_save');
function custom_add_save($postID){
// called after a post or page is saved
if($parent_id = wp_is_post_revision($postID))
{
$postID = $parent_id;
}
if ($_POST['cpi_dropdown_options']) {
update_custom_meta($postID, $_POST['cpi_dropdown_options'], 'cpi_dropdown_options');
}
if ($_POST['cpi_text_option']) {
update_custom_meta($postID, $_POST['cpi_text_option'], 'cpi_text_option');
}
}
function update_custom_meta($postID, $newvalue, $field_name) {
// To create new meta
if(!get_post_meta($postID, $field_name)){
add_post_meta($postID, $field_name, $newvalue);
}else{
// or to update existing meta
update_post_meta($postID, $field_name, $newvalue);
}
}
?>
And there you have it. Quick, go make something interesting!
The quick version? Include wp-load.php and wp-admin/admin-functions.php in a file in the plugin directory, and point your cron there. For those of you with nothing important to do, a long winded explanation:
I ran into a project a few days ago where the client needed a simple plugin put together – read an xml file, pull some information from it, and turn it into a post. Initially, the client wanted to just write straight to the database, but considering we’ve got access to a number of functions perfectly suited for the job, I knew things would be much easier if we turned it into a simple plugin, and ran the built in functions from the admin side.
The plugin came together quite nicely – RSS read, categories created, post inserted, all like a charm. It occurred to me at that point that the client wanted this to run automatically at set intervals – he wanted to schedule a cron job to handle it. However, since the functions I needed to run exist on the admin side, I assumed I’d have to jump through some serious hoops to get a cron to run it.
I formulated a plan, and was all ready to implement it – the plan was to access wp-admin/options.php with the proper get parameters to run the function. It turns out, using curl, you can set a cookie, and then use it to access another page – very cool (big thanks to this post from Russell Heimlich for that; I’m sure more thorough documentation is out there, but his is the post I found).
I still wasnt crazy about the idea though – the extra input with the cron meant more work for the client, more possibility for things to go wrong, and more time spent on support for me. So I decided to see if I could just include the right files from outside the admin section, and poof – it worked. Here’s how it works:
You’ve got to include 2 files to get access to admin side functions: First, wp-load.php. wp-load.php gets everything set up, and fires up wordpress. However, we’re calling this function from the plugin folder, inside the content directory (as opposed to the admin directory) – so when wp-load is called, we’re not going to be in the admin section, and we’re not going to get access to those functions. On the bright side, we also don’t have to deal with WordPress forcing you to login. Since we still need those admin functions, include wp-admin/admin-functions.php. This loads up the admin side and gives us access to the admin functions – and we’re set to go.
So that’s it. Include those 2 files, call wp_insert_post() (or whatever you need to call), and make the client happy.
Off topic – if you’re tired of expensive web hosts, I’ve got a friend who is starting to host for people inexpensively: check out his post on cheap web hosting here.
So, every time I need to write a widget for a client, or for a site I’m working on, I have to fire up google. Even though its something I do relatively often, I just can’t seem to remember what exactly I need to hook into, and how to build the actual widget function. Fortunately, this information is impossible to find all in one place – you’ve got Automattic’s page on widgetizing plugins, which is not just confusing, but the code is actually wrong, and won’t work.
Most of the other sample code I’ve found on how to write a widget for your wordpress plugin is either outdated, or not explained, making it pretty difficult to write and customize your own.
First things first – if you really want to know how this all works, check out the source. Its the best place to figure out what is going on. WordPress widgets source
For my own good as much as yours, here’s the skinny:
First things first – the copypasta edition:
<?php
/*
Plugin Name: Widget Example
Plugin URI: http://yourcodegarage.com/blog
Description: Sample Widget Code
Author: Peter Butler
Author URI: http://yourcodegarage.com/blog/
*/
// Hook into wordpress at the "widgets_init" stage. We need this to get things going.
// We're calling mywidget_init, which will register the widget with wordpress.
add_action("widgets_init", "mywidget_init");
// This is our init function - it's going to register our new widget,
// and if we so please, create a control for it.
function mywidget_init()
{
// This line is required - it cactually registers the widget for use on
// the widgets admin page, and it contains the code to display on the
// front end when the widget is enabled.
register_sidebar_widget('My Custom Widget', 'custom_widget');
register_widget_control('My Custom Widget', 'custom_widget_control', '500', '500');
}
// This is the function called by register_sidebar_widget.
// This is where the action happens - WordPress calls this function to actually display
// the widget in the dynamic sidebar on the front end.
// Note the $args parameter - this is required for the sidebar variables
// ($before_widget, etc) to work properly!
function custom_widget($args) {
// Make sure to extract $args.
extract($args);
// Get the options we set in the widget control (remove this line if there arent any).
$custom_widget_options = get_option('custom_widget_options');
?>
<?php
//echo the html that should display before the widget as set by register_sidebar().
echo $before_widget;
?>
<?php echo $before_title;?>
<?php echo $custom_widget_options['title']; ?>
<?php echo $after_title; ?>
<?php echo $custom_widget_options['text']; ?>
<?php echo $after_widget; ?>
<?php
}
// This is the callback function for our widgets control -
// here we'll keep the code to allow the user to set the widget options.
function custom_widget_control() {
// Check if the option for this widget exists - if it doesnt, set some default values
// and create the option.
if(!get_option('custom_widget_options'))
{
add_option('custom_widget_options', array('title'=>'Custom Text Widget', 'text'=>'This the widget text'));
}
$custom_widget_options = $custom_widget_newoptions = get_option('custom_widget_options');
// Check if new widget options have been posted from the form below -
// if they have, we'll update the option values.
if ($_POST['custom_widget_title']){
$custom_widget_newoptions['title'] = $_POST['custom_widget_title'];
}
if ($_POST['custom_widget_text']){
$custom_widget_newoptions['text'] = $_POST['custom_widget_text'];
}
if($custom_widget_options != $custom_widget_newoptions){
$custom_widget_options = $custom_widget_newoptions;
update_option('custom_widget_options', $custom_widget_options);
}
// Display html for widget form
?>
<p>
<label for="custom_widget_title">Title:<br />
<input
id="custom_widget_title"
name="custom_widget_title"
type="text"
value="<?php echo $custom_widget_options['title']; ?>"/>
</label>
</p>
<p>
<label for="custom_widget_text">Text:<br />
<textarea rows=10 cols=25
id="custom_widget_text"
name="custom_widget_text" ><?php echo $custom_widget_options['text']; ?></textarea>
</label>
</p>
<?php
}
Download the example plugin here
It’s commented fairly well, so that should be a good starting point. For those of you who want a little more explanation, read on…
First things first – we need wordpress to see that our widget is out there just waiting to be implemented. To accomplish this, we’ll hook into the widgets_init action like this:
add_action("widgets_init", "mywidget_init");
Now, when wordpress calls the widgets_init action, our widget initiation function (mywidget_init()) will get called. Read more about actions here.
The function mywidget_init is our callback function in that particular action. When this function gets called, we want to register our widget, as well as our widget control – like this:
function mywidget_init()
{
register_sidebar_widget('My Custom Widget', 'custom_widget');
register_widget_control('My Custom Widget', 'custom_widget_control');
}
The first line registers the widget with wordpress – we’re calling the wordpress function register_sidebar_widget(), which takes these parameters:
function register_sidebar_widget($name, $output_callback, $classname = ”)
The second line registers our widget control. The widget control function will be what allows the user to change any options for the widget on the widgets page on the backend. Here’s a closer look at the register_widget_control() function:
function register_widget_control($name, $control_callback, $width = ”, $height = ”)
Now we’re ready to create our configuration box for the widget – this is what will be displayed on the backend, and allow the user to choose any options you make available. We’ll be using the function we specified in register_widget_control() – custom_widget_control().
To briefly run through this function:
if(!get_option('custom_widget_options'))
{
add_option('custom_widget_options', array('title'=>'Custom Text Widget', 'text'=>'This the widget text'));
}
$custom_widget_options = $custom_widget_newoptions = get_option('custom_widget_options');
First, we get the option we’re going to use to store the configuration infomation for this widget. If it doesnt exist (meaning that this is the first time the widget code has been run, so our plugin has likely just been installed), we’ll create it with some default values. I like to try to keep all the configuration values stored in just one option field, so I prefer to put multiple variables into an array, and serialize them for storage in the database (update – wordpress handles the serializing/unserializing for you with the function maybe_serialize. Read more about it here.)
if ($_POST['custom_widget_title']){
$custom_widget_newoptions['title'] = $_POST['custom_widget_title'];
}
if ($_POST['custom_widget_text']){
$custom_widget_newoptions['text'] = $_POST['custom_widget_text'];
}
if($custom_widget_options != $custom_widget_newoptions){
$custom_widget_options = $custom_widget_newoptions;
update_option('custom_widget_options', $custom_widget_options);
}
Next, we check if values have been posted from the widget configuration form (which we’ll create in a minute). If the values we’re looking for have been posted, we know the user is updating the widget, so we update our wordpress option with the new values.
<p> <label for="custom_widget_title">Title:<br /> <input id="custom_widget_title" name="custom_widget_title" type="text" value="<?php echo $custom_widget_options['title']; ?>"/> </label> </p> <p> <label for="custom_widget_text">Text:<br /> <textarea rows=10 cols=25 id="custom_widget_text" name="custom_widget_text" ><?php echo $custom_widget_options['text']; ?></textarea> </label> </p>
Lastly, we display the actual html form for the widget configuration, making sure to display the values from our option. Putting it all together, here is the function:
function custom_widget_control() {
// Check if the option for this widget exists - if it doesn't, set some default values
// and create the option.
if(!get_option('custom_widget_options'))
{
add_option('custom_widget_options', array('title'=>'Custom Text Widget', 'text'=>'This the widget text'));
}
$custom_widget_options = $custom_widget_newoptions = get_option('custom_widget_options');
// Check if new widget options have been posted from the form below -
// if they have, we'll update the option values.
if ($_POST['custom_widget_title']){
$custom_widget_newoptions['title'] = $_POST['custom_widget_title'];
}
if ($_POST['custom_widget_text']){
$custom_widget_newoptions['text'] = $_POST['custom_widget_text'];
}
if($custom_widget_options != $custom_widget_newoptions){
$custom_widget_options = $custom_widget_newoptions;
update_option('custom_widget_options', $custom_widget_options);
}
// Display html for widget form
?>
<p>
<label for="custom_widget_title">Title:<br />
<input
id="custom_widget_title"
name="custom_widget_title"
type="text"
value="<?php echo $custom_widget_options['title']; ?>"/>
</label>
</p>
<p>
<label for="custom_widget_text">Text:<br />
<textarea rows=10 cols=25
id="custom_widget_text"
name="custom_widget_text" ><?php echo $custom_widget_options['text']; ?></textarea>
</label>
</p>
}
Lastly, we’ve got to display the widget. We’ll need to use the function we called from register_sidebar_widget(), in this case custom_widget.
The first thing we need to make sure of is that we pass in, and extract the variable $args, like this:
function custom_widget($args) {
// Make sure to extract $args.
extract($args);
The widget will display without passing in args, but its necessary, because this is what holds some vital information for our widget. In this particular example, $args holds this information:
Array ( [name] => Right Sidebar [id] => Right Sidebar [before_widget] => <li id="my-custom-widget" class="widget custom_widget"> [after_widget] =></li> [before_title] => <h3 class="widgettitle">[after_title] =></h3> [widget_id] => my-custom-widget [widget_name] => My Custom Widget )
The most important bits that $args holds are the sidebar variables – before_widget, after_widget, before_title, and after_title. Without these, the widget isnt going to display properly. I’ve wasted countless hours (on multiple occasions) trying to figure out why my widget isnt displaying correctly, only to realize that I forgot to pass $args in.
Next, we set up the variables the widget needs to use to display – again, we’ve got them in an array, which is serialized and held in the wp_options database table. To access it, we use get_option(option name).
$custom_widget_options = get_option('custom_widget_options');
Now, it’s just a matter of displaying whatever the widget was intended to display – simple html and php will do the trick here. Make sure to echo $before_widget and $after_widget surrounding the actual content, and $before_title and $after_title surrounding the title. Doing so keeps your widget’s styling in line with the rest of the sidebar.
<?php echo $before_widget;?> <?php echo $before_title;?> <?php echo $custom_widget_options['title']; ?> <?php echo $after_title; ?> <?php echo $custom_widget_options['text']; ?> <?php echo $after_widget; ?>
Putting it all together, here is the widget output function:
function mywidget_init()
{
// This line is required - it cactually registers the widget for use on
// the widgets admin page, and it contains the code to display on the
// front end when the widget is enabled.
register_sidebar_widget('My Custom Widget', 'custom_widget');
register_widget_control('My Custom Widget', 'custom_widget_control', '500', '500');
}
// This is the function called by register_sidebar_widget.
// This is where the action happens - WordPress calls this function to actually display
// the widget in the dynamic sidebar on the front end.
// Note the $args parameter - this is required for the sidebar variables
// ($before_widget, etc) to work properly!
function custom_widget($args) {
// Make sure to extract $args.
extract($args);
// Get the options we set in the widget control (remove this line if there arent any).
$custom_widget_options = get_option('custom_widget_options');
?>
<?php
//echo the html that should display before the widget as set by register_sidebar().
echo $before_widget;
?>
<?php echo $before_title;?>
<?php echo $custom_widget_options['title']; ?>
<?php echo $after_title; ?>
<?php echo $custom_widget_options['text']; ?>
<?php echo $after_widget; ?>
<?php
}
And that’s it! Your widget is ready for action. Now get out there and make a widget!
Recent Comments