Ah, fair $post object. Lets talk about how great you are.
Post Object. WordPress stores all post data (think content, author, tags, etc) in a single object, accessible to themes and plugins on each page load. Basically, this is the place you’re going to go to if you want to get some extra information about a post for whatever clever scheme you’ve got cooked up. Need to know how many “n”s are in this particular post? Talk to the post object. Not sure when this post was originally published? Post object. Looking for lawyers who ride? Now we’re talking – but you want the Law Tigers, not the $post object. Watch their commercials. You won’t regret it.
The post object is available nearly everywhere you’re likely to be looking at a post. If you’re working with a single post page, or an actual page, you’ve got access to that post’s (or page’s) post object anywhere within your theme file. It’s all held in a variable named $post.
If you’re on a page with multiple posts, things are a little trickier but not much. If you’re inside the loop, you’ve got access to a $post object (named $post) referring to the current post in the loop.
What if you want to get at a post that isn’t the one you’re looking at on a particular page – or what if you want to get at one from a plugin, or somewhere where there isn’t a current post explicitly defined? There’s a function for that:
$id = 41; $mypost = get_post($id); print_r($mypost);
get_post() to the rescue! There are, however, a couple of gotchas with get_post.
get_post() gets you. So do I. There’s a second, optional argument to get_post that determines what it spits out at you. It defaults to OBJECT, but you can also pass in ARRAY_A, or ARRAY_N to get an associative array or a numeric array version of the post data.
Find out for yourself! The snippet above uses the function print_r() – it will show you the structure AND data of a particular post object – very useful stuff. Surround it in a <pre> tag, and you’ll be in even better shape – it will display nicely in your browser.
Well played. Here’s a quick rundown on the data the post object gives you:
| Property | Example | Explanation |
|---|---|---|
| $post->post_title | The WordPress $Post Object and You | Title of post. |
| $post->post_excerpt | Learn about the WordPress $Post object! | Manually created post excerpt. If you didn’t purposefully create an excerpt on the add post page, you’re not getting anything here. |
| $post->post_status |
|
Current status of the post. |
| $post->comment_status |
|
Comment status for this particular post. |
| $post->ping_status |
|
Does the current post accept pingbacks and trackbacks? |
| $post->post_password | 123456 | The plaintext password for this post, if there is one. Empty otherwise. |
| $post->post_name | the-wordpress-post-object-and-you | A normalized, sanitized version of the post title, used to generate pretty permalinks. |
| $post->to_ping | http://technorati.com http://someothersitetoping.com | Space separated list of sites to ping which have not been pinged yet. Modified by “Send Trackbacks” field on add post page. |
| $post->pinged | http://technorati.com http://someothersitetoping.com | Space separated list of sites already pinged for this post. |
| $post->post_modified | 2011-09-15 21:21:59 | Time this post was last modified, based on local server time. MySQL timestamp format. |
| $post->post_modified_gmt | 2011-09-15 21:21:59 | Time this post was last modified, based on GMT timezone. MySQL timestamp format. |
| $post->post_content_filtered | Post Content | This field is designed to hold a version of the post for caching, in situations where filters are being run on the post that are “expensive” (slow), and undesireable to run every time. Not used in WP core, may be used by plugins. |
| $post->post_parent | 0 | ID of the parent post. Posts that have parents are generally revisions, or attachments. If the post_parent is 0, this is a bona-fide, original post. |
| $post->guid |
http://codegarage.com/blog/?p=41 |
Global Unique Identifier for the post. According to the documentation page on wordpress.org, this can’t be relied on to actually work as a link to the post, but I’m not totally sure why. Maybe in cases where the site url has changed? |
| $post->menu_order | 0 | Integer determining the order in a list of posts. Generally used for pages in menus, but can be used by plugins for special ordering. |
| $post->post_type |
|
The particular type of post this is. Attachments are generally images, pdfs, etc. Posts and pages are self explanatory. |
| $post->mime_type | image/png | Mime type for attachments. |
| $post->comment_count | 14 | Number of comments on this post currently. |
| $post->post_ancestors | array | Array of parent posts for this post. |
I think that about covers it. One last question you might have:
How do I get WordPress to spit out properly formatted post content?
Good luck!
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 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.
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!
As you may have noticed in a post I made a few days ago about widetizing wordpress plugins, I mentioned that we needed to serialize our variables before we created them as options in wordpress. As it turns out, this isn’t the case – WordPress does it for you when you go to update or create an option. This morning, while reading a post on wpengineer.com about wordpress options, I noticed that in their sample code, they weren’t serializing arrays or objects before creating them as options. Michael, the author, set me straight on why this is ok.
As it turns out, WordPress is one step ahead of me. Maybe_serialize() is called a number of times throughout wordpress, relating to these items:
So there you go. Use all the arrays and objects you want in post meta, user meta, and options – throw caution to the wind, and put them straight in. WordPress will handle the boring stuff.
Recent Comments