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!
WordPress is an amazingly flexible, powerful content management system – it can do a lot of things for a lot of different people, and can can be contorted to match the requirements of impossibly different businesses. All for free.
Of course. Lets talk about how you can go about making small customizations to your WordPress based site. There are routes to take for people of all ability levels – so don’t be afraid if you’re still not exactly sure what “hosting” means.
I’m going to give 2 paths here, one for people who don’t know html and css from arugula, and one for those who do, even if it’s just barely.
Over the past 12-18 months, the WordPress community has exploded with a new class of themes – heavily customizable and easy to use, even for those with little or no html and css ability. I’m going to talk about 3 themes here – 2 paid, and one free. Feel free to chime in in the comments with your personal favorite.
Headway is my favorite. It’s not free, in fact, it’s not even cheap – but in my opinion, their visual editor is really fantastic – and just what a beginning WordPress user needs to get them up and running with a great looking, customized theme. Click here to visit Headway.
Thesis has been around since the beginning of paid themes. It’s hugely popular and has a rabid following. It’s not my favorite for a number of reasons, but how wrong can 35,000 people be? Click here to visit Thesis
Atahualpa is another tricky one. It’s very popular, and refreshingly, it’s free! However, there is a pretty steep learning curve that comes along with it. If you’ve got the patience to power through the learning stage, you’ll no doubt be very excited with the end product. Click here to visit the Atahualpa homepage
The other option is a little less glamourous, and a lot more migraine inducing, but the possibilities are limitless. WordPress works on a templating system that is both easy to use, and robust enough to let you do anything you want it to. The kicker is: you need to learn how HTML, CSS, and even a little bit of PHP if you’re going to make this work. You don’t exactly need to be an expert in any of them to make small changes to an existing theme though. Here’s the quick overview, and some links to get you pointed in the right direction:
Nearly every WordPress theme consists of the same basic set of files, listed here:
That is, unfortunately, not even close to a complete list. Fortunately, there’s a handy diagram at this page on wordpress.org.
Now, you at least know where to start looking – all that’s left is to figure out what to do once you get there. Here are a couple of great tutorials to get you on your way:
HTML Tutorial
CSS Tutorial
In one of many, many strokes of genius, the WordPress core developers threw in a bit of code to allow users (ok, other developers) to define a custom user table, and a custom usermeta table for a WordPress install.
In it’s simplest form, you can point your WordPress user table at that of another blog on your server. Doing so means both blogs (and why stop at 2?) share user information: passwords, usernames, author bios, etc etc. If you’ve got a site that requires numerous different, separate WordPress installs (think something along the lines of wired.com), but the same authors often write on many or all of them, this is a great, and easy solution.
Yes Sir. Just slap this code in your wp-config file:
define('CUSTOM_USER_TABLE','new_user_table');
define('CUSTOM_USER_META_TABLE', 'new_usermeta_table');
It’s pretty self explanatory from there – just define a custom user table, and a custom usermeta table, and you’re good to go. Want your users to share login info across different blogs, but be able to have a different bio for each one? Define a custom user table, but leave the default user_meta table. Everything stored in the users table (ID, login, password, nicename, email, url, and display name, among other things) will stay the same across all blogs. Everything else (nickname, user level, First Name, Last Name, and many other things), will be blog specific.
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!
Recent Comments