From the blog

Welcome to the blog, I tend to blog about work related things, so you'll often find useful snippets of code for Wordpress amongst other things.

How to use dig to get the TTL (time to load) of a domain

Obtaining the TTL for a domain is quite simple.

Open up a terminal and meet your new friend ‘dig’.

Type the follow, replacing my website url with your own.

dig +nocmd davidheward.com +noall +answer

The response you will get is:-

davidheward.com.	3496	IN	A	87.124.86.12

Your friend is 3496 this is your domains TTL.

Which is 3,496 seconds, or almost 1 hour.

Enjoy.

Tagged: Leave a Comment

Enqueue WordPress script on certain theme template pages only

Enqueuing scripts the proper way in WordPress can help avoid annoying javascript problems and allows us to specify dependancies of our scripts I.E. jQuery, so that WordPress may load the specified scripts before our script, thus eliminating problems.

I quite often find myself wanting to enqueue scripts into one particular page template rather than loosely across my entire site, in a vein attempt to try and keep the site as efficient as I possibly can.

So I thought I’d share with you how to achieve that.

Firstly open up your functions.php file.

if(!function_exists('register_my_scripts')):
    function register_my_scripts(){

    }
endif;

Add the above function. This function will control enqueueing scripts for your theme.
Now we must tell WordPress through registering an action that we want it to check this function when it enqueues scripts in the wp_head(); function called in the header.php file.

We can do this by adding this line of code to our functions.php file.

add_action('wp_enqueue_scripts', 'register_my_scripts');

And wollah, now WordPress will call our function when it attempts to register scripts. Now hopefully you may already be familiar with the WordPress functions wp_register_script and wp_enqueue_script

If not heres a rundown.

wp_register_script
A safe way of registring javascripts in WordPress for later use with wp_enqueue_script().

<?php wp_register_script( $handle, $src, $deps, $ver, $in_footer ); ?>

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to problems.

For further details see the wordpress wp_register_script page »

wp_enqueue_script
A safe way of adding javascripts to a WordPress generated page. Basically, include the script if it hasn’t already been included, and load the one that WordPress ships.

usage:

wp_enqueue_script(
     $handle
    ,$src
    ,$deps
    ,$ver
    ,$in_footer
);

Use the wp_enqueue_scripts action to call this function, or admin_enqueue_scripts to call it on the admin side. Calling it outside of an action can lead to problems.

For further details see the wordpress wp_enqueue_script page »

Given that you now have a reasonable grasp of whats going on lets move this forward, first we want to register our script name with WordPress and then we want to enqueue it.

This can be quite easily done with the following.

//Register our script
wp_register_script('my-script',
get_template_directory_uri() . '/assets/js/my-script.js',
array('jquery'),
'1.0' );

//Enqueue the script
wp_enqueue_script('my-script');

Put this inside our earlier defined function of register_my_scripts. First of all I register my-script and then I enqueue it in the load schedule with wp_enqueue_script.

How to do this only on a particular page?

The answer is very easily. Inside the function we can simply wrap the register and enqueue script actions with the following.

if(is_page_template('about.php')):
// code
endif;

Sweet as a nut. See below for the full finished code example.

The full thing

if(!function_exists('register_my_scripts')):
    function register_my_scripts(){
        if(is_page_template('about.php')):
            //Register our script
            wp_register_script('my-script',
            get_template_directory_uri() . '/assets/js/my-script.js',
            array('jquery'),
            '1.0' );

            //Enqueue the script
            wp_enqueue_script('my-script');
	endif;
    }
endif;

Some points

You will notice that in my wp_register_script I have used jquery as a dependancy this means that it will now be loaded by WordPress after jquery, neat huh?

You’ll also notice that I have put a version of 1.0 into the register, this is handy for upgrading the scripts to prevent caching problems, as the version is appended to the end of the file name like so:


http://localhost:8888/my-site/wp-content/themes/my-theme/assets/js/my-script.js?ver=1.0

If you make some changes and want to avoid any caching issues, simply upgrade the version to 1.1 in your code.

Tagged: Leave a Comment

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.

Tagged: Leave a Comment

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.

Tagged: Leave a Comment

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.

Tagged: Leave a Comment

How to create WordPress pages with just pure PHP

I’ve seen alot of people ask how to create pages within WordPress with some simple PHP code so I thought i’d give answering it a go.

You’ll be pleased to know that the solution is pretty straight forward and nothing to strenuous.

We’ll start off by defining a function to handle creating pages in WordPress, you could use this function in your themes function file or indeed in any custom WordPress Plugin.


if(!function_exists('daves_create_page')):
    function daves_create_page( $slug, $option, $page_title = '', $page_content = '', $post_parent = 0){
        global $wpdb;
        $option_value = get_option($option);

        if ($option_value>0) :
            if (get_post( $option_value )) :
	        // Page exists
	        return;
	    endif;
	endif;

	$page_found = $wpdb->get_var("SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '$slug' LIMIT 1;");
	if ($page_found) :
	    // Page exists
	    return;
	endif;

	$page_data = array(
            'post_status' => 'publish',
            'post_type' => 'page',
            'post_author' => 1,
            'post_name' => $slug,
            'post_title' => $page_title,
            'post_content' => $page_content,
            'post_parent' => $post_parent,
            'comment_status' => 'closed'
        );

        $page_id = wp_insert_post($page_data);

        update_option($option, $page_id);
    }
endif;

After defining this function we can call it into play very simply with the following.


daves_create_page(
    esc_sql( _x('example_page', 'page_slug', 'davespage') ),
    'daves_page_id',
    __('Example Page', 'davespage'),
    'Some example content.'
);

Hope this helps some people out, as you can see, pretty straight forward and unobtrusive.

Tagged: Leave a Comment

A great quote

I just stumbled across this quote tonight and felt it was pretty relevant to me.

It does not do to dwell on dreams, and forget to live.

Re-enforces my earlier post, that work should co-incide with life, not dictate it.

To be happy with both, you must strike a balance.

Leave a Comment

Make sure judgement doesn’t cloud the journey

Earlier today I was laying in bath (as you do, with a broken ankle) one leg dangled out the side, rather uncomfortably. Attempting to relax, I kicked back, reflecting the last few weeks of life. As an overview, they’ve both been fortunate and unfortunate in different ways. Almost as if one was meant to happen to help improve the other.

So what am I going on about? Well, a little under 5 weeks ago today, I broke my ankle, after a heavy & damn right clumsy (arguably malicious) challenge on me at football. This was both painful and inconvenient (and still continues to be so), but what it did give me was plenty of time to think, and with the wonders of technology work from my bed. The extra time, which I might have normally filled with other activities, I used to plan and re-evaluate my working life.

For those of you that don’t already know, I run an web based media company called Bytewire and have been doing so for 3 years, since we first started up. I kicked straight out of uni into this and it’s been a roller coaster ride from day one.

Anybody who regular reads my blog will remember I wrote about a bit of a predicament we we’re having after being 3 years down the line and having not really achieved our goals as a company (least not the dream). If you didn’t read it, catch it here – Why web design is something I got into »

It’s definitely worth reading first before this post.

Now, in this previous post I promised a follow up post, so here we have it.

Another few months have past and it’s been all change with my working life and company direction. After a great deal of thinking and deliberation we sat back and said, you know what.

What do WE want to be getting out of this?

Personally, professionally, and everything else that come’s with it. And it was really refreshing, like, really, really refreshing. It felt like alot of what we buried our heads in the sand with, previously, was finally being addressed.

Now I guess you’ll be wondering what sort of things we talked about and what that meant. But I want to keep this post on a strictly personal level, so i’m not going to go into all the ins and outs of our start up company Bytewire’s improvements.

As any Entrepreneur or business owner will tell you, you start out with a dream, something you think will be huge, even if it is totally unattainable in your mind right now! You’ve got to dream big. Those that do will change the world. We set out 3 years ago to build a game, then further that with follow up titles and expansions.

Truth is, we never quite made it. We received investment from a company and we blew the opportunities this very well could have opened to us. Reason we blew it, in-experience. We thought hey, you know what, we can keep all this investment money and try and make it ourselves and we would be better off. WRONG. So very WRONG. People are STRENGTH. More people equals greater STRENGTH (given you get the right people of course). Expansion was the lost KEY.

Lesson: Never consolidate in a start up, always try to expand. Of course use your head to make logical decisions. But never sit, not making the most of your resources.

What this meant for us, is, we slowly dwindled away vast amounts of our initial investment money. To the point we we’re at a couple of months ago. We recently made our final payment on our current office, leaving just 3 remaining months (probably less) before we would need to commit to more time their, find another, or leave.

After discussion, this would likely be our penultimate few months, if no improvements we’re made.

It was a stressful time.

During the few nights I spent in hospital I began to think once the last rent payment is made, it is make or break time. 3 years down the line just turned 25, i’m no longer a kid with a big dream. I’m an adult who want’s to get something out of life, like a house, a new car, perhaps even a family (shudders), fly the roost and all that etc etc.

It dawned on me that, we need to make work more about us, what we need, and what we enjoy. Work should fit around our lives, not dictate them. We needed to start taking ourselves more seriously and doing all we can to make things work, in an all out attempt to make it WORTHWHILE. And in the end be able to sit back and say you know what if this isn’t worthwhile, then maybe we should do something else.

And this is the KEY for me. I love what I do, but in reflection we did it the wrong way round. We’re now at a point, as developers, we should have been at from the very start, ideally. Which hampered our ability in the beginning. But Cest la vie, such is the card we dealt.

As all start up founders will know the people that have to make the greatest sacrifice are ME & YOU, the owners. When you start out, you have to accept, long unsociable hours, little financial rewards, and generally difficult times. And we most certainly have done this, for 3 years now. It’s gone past it’s honey moon period, when enthusiasm was rife. It’s gone into, this seriously needs to be working, or we cannot simply carry on blindly doing it. Life needs a shake up every now and again.

What we did was to both go away and identify things we would like to happen, a few things cropped up. One obvious thing was financially things had to improve, best job on the planet or not, if someone working in a Supermarket pulls more than our average wage a month, then something is wrong (of course absolutely no offense meant by this, i’m just using it as a benchmark, people can relate to). Learning new things, and tools to do our jobs better we’re amongst other mentioned things.

What I suggested we did was treat the next 3 months as if it we’re really a game. Stop all this long term thinking, like if we do that we won’t have any money left in 3 months. I mean who the f*ck cares if there’s no money left if what your doing does not financially support you right now! And you’ve already given it the time you feel it was due to flourish. Right?

Or planning for events like making no more money. If you don’t make any money in 3 months there’s a real business problem, right here, right now. Solve it, or it’s never going to be worth it.

Do not mistake what I am saying here for the fact we do it just for the money. It’s really not true. But as mentioned earlier it’s a key factor in life, moving out, and growing up. It cannot be forgotten.

Which leads me excellently to the title of this post. Judgement might tell you that, paying yourself more or rewarding yourself more often, can’t be done unless you’ve hit ridiculous milestones in your bank account. But you shouldn’t be thinking about that. Do not waste your time planning for the long term until you have something worth planning / protecting for! Focus on the short term, make yourself happy (don’t be greedy), focus on the reasons you work for yourself, and more importantly the benefits.

In business you must strike a balance between risk and safety. Without risk there can be little gains. Risks are everywhere you’ll take them all the time, but when it comes to money, some people, are just less comfortable with taking risk than others.

As people we’ve all got a bit of stick or twist in us, how you answer, with personal money in your hand should be different to business money.

With business you must leave your personal money management at home.

Don’t get me wrong there is a big difference between reckless and calculated. And only you can decide where the line may lie. But with everything in life, you do need to be able to draw lines under things and have the integrity enough to hold your head high no matter what the outcome. And also the knowledge enough to walk away from things which are not working, but still having gained valuable and useful experience.

It’s all about the experience and the journey. If a ship opens its sails, it’ll most likely go somewhere. If you sit ashore, unsure of where the open water might take you, you’ll sure as hell go nowhere.

When you get somewhere, a long way down the road, then you plan for the future.

Right now, just live for the moment.

Tagged: Leave a Comment

Correct way to add CSS to WordPress Plugin Backend

Many of us have dabbled with making our own WordPress plugins, but what alot of people forget is we need to make sure we’re as compatible with WordPress going forward as can be.

Over the last 3-5 months I’ve really started to discover the hidden power of WordPress and today i’m blogging about another find.

It’s quite a simple topic really. Many of you will want to include your own custom stylesheets with your plugins, but what’s important is keeping the integrity of your WordPress plugin intact.

So whats the correct way to Enqueue your css stylesheet?

There is a couple of ways in which you could achieve it, but being prudent is best.
Include the stylesheet only in the admin pages that you absolutely need to, in the case of the backend, only on the submenu pages you need to.

I am of course assuming here that your pretty familiar with the plugin backend and that you know how to create sub menu pages for your WordPress plugin.

$page = add_submenu_page(
    'edit.php',
    __( 'My Plugin', 'myPlugin' ),
    __( 'My Plugin', 'myPlugin' ),
    'administrator',
    __FILE__,
    'my_plugin_manage_menu' );

    /* Using registered $page handle to hook stylesheet loading */
   add_action( 'admin_print_styles-' . $page, 'your_plugin_styles' );

This would of course normally be wrapped in a function or class, whichever your coding style prefers.

We are telling WordPress in the above example to add an action to call our custom function ‘your_plugin_styles’ on printing styles for the page WordPress object reference now contained within $page.

// Hook somethings up in our plugins init function
add_action( 'admin_init', 'your_plugin_admin_init' );

Next, I have added an action to be fired on ‘admin_init’ to call ‘your_plugin_admin_init’.

And what i’ll do inside this is call a custom_forms.css file that I need to use for some styling on the backend of this plugin. I’ve also housed it in a css/ folder within my plugin directory for convenience.

function your_plugin_admin_init(){
    wp_register_style( 'yourCustomFormCss', plugins_url('css/custom_forms.css', __FILE__) );
}

And finally we enqueue our script using wp_enqueue_style

function your_plugin_styles(){
    wp_enqueue_style( 'yourCustomFormCss');
}

And this is our working procedure.

Bringing it altogether.

We first fire our plugins init function called ‘your_plugin_admin_init’ inside this we register our css style with WordPress. Ready to be called later. Then whilst registering our menus, we tell WordPress on this admin page ONLY, to fire our custom css calling function ‘your_plugin_styles’ and from within that we enqueue our previously registered script ‘yourCustomFormCss’ using ‘wp_enqueue_style’.

Some useful links

Tagged: Leave a Comment

Link color transitioning with css 3

One of my new favourite tools is css3. I love how for the tech savvy I can add a level of detail and luxury to a web page with no fallback problems for lesser browsers.

One of my current favourites is color transitioning in css3 for such things as links.

If you give it a go i’m sure you’ll agree with me, that it rules.

It’s also really incredibly simple!

First of all we start with a regular href tag and a :hover state declaration.

a{
   color:#000;
}
a:hover{color:#f00;}

Then we add our css3 transition, first of all just for webkit browsers.

a{
   color:#000;
   -webkit-transition:color 1s ease-in;
}
a:hover{color:#f00;}

Now we improve it by adding more extensive browser support.

a {
   color:#000;
   -webkit-transition:color 1s ease-in;
   -moz-transition:color 1s ease-in;
   -o-transition:color 1s ease-in;
   transition:color 1s ease-in;
}

And then you have it a simple transition from your main color to your hover state color. With no JS, jQuery or any other javascript libraries help.

Wicked, eh?

Tagged: 2 Comments