Categories
PHP Programming Wordpress Development

WordPress 3 Custom Post Type Tutorial

When WordPress 3.0 was released, all the hype was about something called “custom post types”.  Custom post types basically allow you to add your own content types to WordPress.  Lets say for instance that you want to create a newsletter.  A newsletter in your case, is a quick descriptions followed by the excerpts from several regular posts.  By default, WordPress doesn’t support this.  However, with custom post types we can add out own “Newsletter” post type and get to work.

Wordpress Newsletter Cusotm Post Type

Step 1:  Register the Custom Post Type

When creating a new custom post type, the first thing you need to do is register it with your WordPress install.  This can happen at the theme or plugin level.  In my trials with custom post types, I’ve always done it at the plugin level (mainly because I’m a developer, not a designer).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Set up custom post type variables.
$labels = array(
   'name' => _x('Newsletters', 'post type general name'),
   'singular_name' => _x('Newsletter', 'post type singular name'),
   'add_new' => _x('Add New', 'Newsletter'),
   'add_new_item' => __('Add New Newsletter'),
   'edit_item' => __('Edit Newsletter'),
   'new_item' => __('New Newsletter'),
   'view_item' => __('View Newsletter'),
   'search_items' => __('Search Newsletters'),
   'not_found' =>  __('Nothing found'),
   'not_found_in_trash' => __('Nothing found in Trash'),
   'parent_item_colon' => ''
);
 
$args = array(
   'labels' => $labels,
   'public' => true,
   publicly_queryable' => true,
   'show_ui' => true,
   'query_var' => true,
   'menu_icon' => get_stylesheet_directory_uri() . '/images/newsletter.gif',
   'rewrite' => true,
   'capability_type' => 'post',
   'hierarchical' => false,
   'menu_position' => 20,
   'supports' => array('title','editor', 'excerpt')
);
 
//Register the newsletter post type.
register_post_type( 'newsletter' , $args );

Now, lets disect this a bit so you know what’s going on.

  • Labels
    • name – The name of your custom post type.  Usually this is the plural form of it.
    • singular_name – This is the singular form of your plural name.
    • add_new – Normally when you add a post, you click “Add new”.  It’s the same thing for this example.  However, you could make it say “Be more awesome! Add a newsletter!” (if you REALLY wanted to).
    • edit_item – Same as add_new.  You can change how the edit link is displayed.
    • new_item – When you first create your new newletter, this is what it will describe it as.  Once you have a title on it, it will display that instead.
    • For more information on these, I suggest the WordPress Codex.
  • Args
    • labels – General label information for your custom post type.
    • public – Should this be made available to all users?
    • publicly_queryable – Should the public be able to run queries against your post type?
    • show_ui – Do you need a user interface?
    • menu_icon – Path to the icon that is displayed in the admin.
    • rewrite – Should WordPress attempt to make the urls friendly?
    • supports – This bit is pretty important.  This is where you describe what is shown in the admin.  Currently I have “title”, “editor”, and “excerpt”.  You can also extend this with your own stuff later.
    • For more information on these, I suggest the WordPress Codex.
  • register_post_type – This hook is how you register your shiny new custom post type with WordPress 3.0.  First argument is a unique name that you give to your custom post type.  The second argument is the array that was defined above.

Step 2: Custom Categories (Taxonomy) [optional]

One of the nice things about custom post types in WordPress 3 is that you don’t have to use the same categories (taxonomy) as your other posts  and pages.  Registering a new taxonomy for your custom post type is very easy.

1
2
3
4
5
6
7
8
9
//Create taxonomy for categorizing newsletters
register_taxonomy(
   "Categories",
   array("newsletter"),
   array("hierarchical" => true,
      "label" => "Categories",
      "singular_label" => "Category",
      "rewrite" => true)
);

How this works is fairly straight forward.  The first argument is what you’d like your new post type categories to be called.  In this example, I opted for simplicity and went with “Categories”.  The second argument is the post types that you would like this taxonomy to show up on.  Since we only want it on our new post type, I’ve defined it as such.  The third argument is for options (lables, rewrite on/off, etc).

Step 3:  Your done!

Really, it’s that easy.  If you want to make it really useful, you need to add meta boxes to admin interface so that you can do sweet custom content.  But at it’s bare minimum, this is all you need.

If there is sufficient interest, I can go into deeper detail about making a plugin with a custom post type.  Also, if you need help, drop a comment and I’d be happy to give your problem a shot.

Categories
PHP Programming

PHP Function Of The Day: ob_end_clean()

Sometimes you get in to a situation where you are working in an environment that drops everything into an output buffer before it spits it out the browser. In most languages this is called “output buffering”. The problem with having EVERYTHING buffered is being able to do special stuff like dynamic XML documents.

My solution to this little pickle was to just drop everything from the current output buffer and then kill the process after I’m done with it. To do this, just execute “ob_end_clean()” right before the functions/objects/code you need to execute. What “ob_end_clean()” does is drops all information that is currently stored in the output buffer, and then stops the buffering anything after it.

One “gotch ya” moment I had using this function was that it doesn’t end ALL cases of output buffering. If for some strange reason there is nested buffering going on, you’ll need to call the function as many times as it takes to get to the top of the call stack.

http://us2.php.net/manual/en/function.ob-end-clean.php

Categories
PHP Programming

Converting MySQL dateTime to RFC-822 (RSS pubDate) in PHP

I had the need to convert a MySQL datetime time stamp into a format accepted by the RSS 2.0 specification. To get the first part, you can do a SQL query like the following:

1
SELECT DATE_FORMAT(dateTimeColumn, '%a, %d %b %Y %T') AS rssPubDate FROM yourTable

After that, you need to get the timezone, which can be accomplished by using this:

1
$timeZone = date('T');

So lets say you store the rssPubDate from MySQL in a variable called $rssPubDate, all you need to do is $rssPubDate .= ” {$timeZone}”;

That’s it! You now have a RFC-822 compliant time stamp.

Categories
PHP Programming

Supressing Error Messages in PHP

Every once in awhile PHP decides to throw some errors.  Usually it’s because you didn’t do something right, but what if it’s throwing errors anyways?  What if you are on a production server and you need to suppress the errors?

In that case add the following the the top of your file, or include it as a header.

{code type=PHP}
ini_set(“display_errors”, 0);
ini_set(“log_errors”, 1);
{/code}

Optionally, if only a particular statement is throwing an error, you can do this:

{code type=PHP}

$myName = @get_name();

{/code}

The “@” symbol will suppress any errors that the calling function makes.

Remember, suppressing errors is no substitute for good coding.  But, sometimes you do what you have to do.

Categories
PHP Programming

Showing All Errors in PHP

When I was first starting to create web sites with PHP, I struggled with getting error reporting turned on.  Turns out, that you can have it enable at the server, or in the document, or in both.  For development, it’s probably a good idea to have this at the top of script:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This will allow php to display all errors, notices, and warnings.  Simple things like developing with error reporting full on like this help prevent security breaches and unknown application behavior.

Categories
PHP Programming Wordpress Development

WP Hacker News Plugin

I’ve been on a WordPress kick lately, and decided that Hacker News needed a WordPress plugin.  This plugin simply places a nice little Y Combinator badge in the upper right-hand corner of your post, with a link that says “Submit to HN”.  If you’d like to check it out, it’s used on this post.

Also, it can be downloaded here.

If you have any questions or need support, please leave a comment.

Categories
PHP Programming

Disabling Internet Explorer Cross Site Scripting Filter (XSS)

A client of mine recently tasked me with figuring out why the newer versions of IE were throwing a Cross Site Scripting (XSS) error.  For the life of me,  couldn’t figure out why.  Maybe it was because they were submitting a form to another server?  Or perhaps because the Javascript was closing the window when it was done?  I don’t know.  But, I did find a nice little trick that allows you to disable the Cross Site Scripting(XSS) filter in IE.

All that you need to do is add “X-XSS-Protection: 0” to the response header.  For instance, to disable the Cross Site Scripting(XSS) filter all you do is:

header(“X-XSS-Protection: 0”);

That’s it.  Usually that will resolve any XSS errors you have.  It may not be the best solution from a security stand point, but it’ll work in a pinch,

Categories
PHP Programming

PHP Type Evaluation

Aside from grad school drama, I learned something new the other day about PHP.  In PHP, there are two ways to look for equality: “==” and “===”.

$a = “1”;
$b = 1;
if($a == $b) { echo “True”; } else { echo “False”; }
if($a === $b) { echo “True”; } else { echo “False”; }

The first if statement would evaluate to true because it only evaluates the value.  The second if statement would evaluate to false, because it evaluates both value AND type.