Archive for December, 2011

How to add custom meta boxes to WordPress

Many of us want to add custom meta boxes to WordPress post types and doing so is a relevantly easy jaunt, in this tutorial i’m going to show you how from start to finish to add a Custom meta box to your admin pages.

I’m going to run through a very simple example of adding your own custom-meta to a page called ‘homepage’ from start to finish.

First of all pull up your functions.php file.

Now add the following

add_action('add_meta_boxes',array(&$my_custom_meta,'home_create'));

Notice how we are passing an array with reference to the variable $my_custom_meta here. $mss_custom_meta is a class we are now going to define which will handle our custom meta handling.

Create a folder called includes/ and within create a file called custom-meta.php

Within custom-meta.php enter the following.

if(!class_exists('MY_Custom_Meta_Handler')):
    class MY_Custom_Meta_Handler{
        function __construct(){}
        function home_create(){}
    }
endif;

Save this and head back to your functions.php file.

You’ll hopefully remember from earlier that we were passing a reference of $my_custom_meta around. Now we need to define it.

require_once(dirname(__FILE__)."/includes/custom-meta.php");
$my_custom_meta = new MY_Custom_Meta_Handler;

Now we have our class in the $my_custom_meta variable ready to be passed in our add_action call already defined.

We’ve now done the very basis setup and we’ve got ourselves an action calling a class. Now we need to define what we want our extra custom fields to look like and what we want them to do. We’ll start by defining another action, where we want it to apply to and the function designated to control the looks of it.

add_meta_box('my_homepage_meta','Home Page Info',array(&$this,'home_display'),'page','normal','high');

As defined by WordPress:

add_meta_box( $id, $title, $callback, $page, $context, $priority, $callback_args );

Here we have said we want to give this meta_box the id of my_homepage_meta, the display title of Home Page Info, passed this class by reference using this and home_display function. We’ve then defined the page which in this case we’ve left as a ‘page’. Although it could be a post, page or any other custom post type you define.

$page
(string) (required) The type of Write screen on which to show the edit screen section (‘post’, ‘page’, ‘link’, or ‘custom_post_type’ where custom_post_type is the custom post type slug)
Default: None

$context
(string) (optional) The part of the page where the edit screen section should be shown (‘normal’, ‘advanced’, or ‘side’). (Note that ‘side’ doesn’t exist before 2.7)
Default: ‘advanced’

$priority
(string) (optional) The priority within the context where the boxes should show (‘high’, ‘core’, ‘default’ or ‘low’)
Default: ‘default’

Now that, that’s in we need to focus on the home_create function within our class. The home_create function is going to be repsonsible for outputting our form to the WordPress backend.

function home_create($post){
$my_home_meta_some_text = get_post_meta($post->ID, '_my_home_meta_some_text', TRUE);
?>
<table class="form-table">
<tr>
<th scope="row"><label for="my_home_meta_some_text">Some text:</label></th><td><input type="text" name="my_home_meta_some_text" id="my_home_meta_some_text" value="<?php echo esc_attr($my_home_meta_some_text); ?>">
</td>
</tr>
</table>
<?php
}

So here i’ve created a form input and got the current value out of the database for this value using the get_post_meta() function.

To finish up we now need a function which is responsible for saving out this new meta data. Head into the class once more and locate the __construct() function and add the following line.

function __construct(){
    add_action('save_post',array(&$this,'home_save'));
}

This adds an action to the action save_post which means everytime a post is saved it will be fired. Now lets define our home_save function.

function home_save($post_id){
if(isset($_POST['my_home_meta_some_text'])):
update_post_meta($post_id, '_my_home_meta_some_text', esc_attr($_POST['my_home_meta_some_text']) );
endif;
}

And wallah! We now have some custom meta saved to this page! With minimal effort. Here’s the finished file and code to add to the functions.php file.

Functions.php

require_once(dirname(__FILE__)."/includes/custom-meta.php");
$my_custom_meta = new MY_Custom_Meta_Handler;
add_action('add_meta_boxes',array(&$my_custom_meta,'home_create'));

includes/custom-meta.php

if(!class_exists('MY_Custom_Meta_Handler')):
    class MY_Custom_Meta_Handler{
        function __construct(){
            add_action('save_post',array(&$this,'home_save'));
        }
        function home_create($post){
        $my_home_meta_some_text = get_post_meta($post->ID, '_my_home_meta_some_text', TRUE);
        ?>
        <table class="form-table">
        <tr>
        <th scope="row"><label for="my_home_meta_some_text">Some text:</label></th><td><input type="text" name="my_home_meta_some_text" id="my_home_meta_some_text" value="<?php echo esc_attr($my_home_meta_some_text); ?>">
        </td>
        </tr>
        </table>
        <?php
        }
        function home_save($post_id){
            if(isset($_POST['my_home_meta_some_text'])):
                update_post_meta($post_id, '_my_home_meta_some_text', esc_attr($_POST['my_home_meta_some_text']) );
            endif;
        }
    }
endif;

And there we have it, how to create custom meta boxes in WordPress.

Custom URL structure in WordPress using filters and hooks

WordPress, as we all know is one of the greatest open source website platforms available right now and what with it being open source and all that pretty much anything is possible with it.

You just need to dig deep enough and most of the time you’ll find the answer. I was looking for a simple way to rewrite a custom url to a page within wordpress.

I wanted to recreate a url like this dashboard/authorise/2/ with the 2 being an id for the object I am trying to authorise.

My page called ‘authorise’ with a page parent of dashboard would look out for the presence of the passed parameter and use it within the page to attempt an authorisation request for that object.

After alot of digging I found the answer within WordPress.

In the end I needed to use a combination of 3 hooks although one is not necessarily 100% necessary. All of the below snippets should reside in your functions.php wordpress theme file.

function flush_rewrite(){
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}
add_action('init', 'flush_rewrite');

This function simply flushes the WordPress re-write rules to the database. The second hook adds the expected parameter to the WordPress query vars filter and is required so that our page can pull the variable out later.

function add_wp_query_vars($public_query_vars){
    $public_query_vars[] = 'auth_id';
    return $public_query_vars;
}
add_filter('query_vars', 'add_wp_query_vars');

The third and final hook is to the “generate_rewrite_rules” hook, and it allow us to add a custom WordPress re-write rule for our new URL structure.

function authorise_rewrite_rules($wp_rewrite){
    $wp_rewrite->rules = array(
        'dashboard/authorise/(.*)/?' => 'index.php?pagename=authorise&auth_id='.$wp_rewrite->preg_index(1)
    ) + $wp_rewrite->rules;
}
add_action('generate_rewrite_rules', 'authorise_rewrite_rules');

As you can see i’ve included the full url including the parent of the page and re-written the arguments to auth_id. The final bit of information you now need to know is how to get this variable for usage on your page, its quite simple really.

global $wp_query;
echo 'Auth_id: '.$wp_query->get('auth_id');

Note: You do not have to use pagename like I have in my rewrite rule you could be using the “page_id” method instead, I just prefer pagename as it’s a bit more universal across installs. There you have it a simple way to keep nice URL’s within WordPress.

UK Government should practise top down innovation

I was thinking about this last night and it occurred to me that really our government does not practise innovation itself. Long gone are the days where the government used its own resources to better itself, instead they repeatedly get taken to the highway by medium / large businesses, and quite frankly have their pants pulled down. Business is business, but at times it seems like the government should be running itself as a more stringently run organisation, even dare I say it, as a normal business. If it’s cheaper to build a project team and do the project yourself, bloody well do it. Even such things as building railways. Pay an architect top wack and then run the labour as a business on a budget. Don’t get taken to the highway by a firm who say they can do the lot for huge amounts of extra money. Most shocking of all is most of these medium / large businesses will charge above normal rates to do something for their own country. Wheres the pride in that! There’s no pride anymore, no unison, no belief.

Government believes they have no bargaining power nor alternative so in alot of cases they ignore or pay up. I think the public should be involved in balleting for what the people want. I don’t want some toffee nosed tosser who drives his jag/merc/bentley into central london to work. Then claims it all back on expenses, which we indadvertedly pay for, deciding what the majority of people in this country need. We as the people who pay the taxes should have our say as to what gets done and what doesn’t. Even a more informative online portal showing more transparency over what they’ve paid for what projects and why etc would be a great start.

Whats happened to the days of a proud Britain, a united Britain. Long gone in my opinion.

PS I don’t pretend to know anything about the above, I just like to rant.