nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Category: Wordpress

Posts on anything related to the Wordpress blogging platform including themes, plug-ins and general tips.

Converting a WordPress post to a custom post type

Update: There is now a plug-in that does this for you called Post Type Switcher so you don’t have to get your hands dirty with the SQL (thanks Bruno!). Another plug-in called Convert Post Types is also available that does the job for you, Thanks to Steve for that one.

With the release of WordPress 3.0, developers now have the ability to create custom post types by adding a few lines of code to a themes functions.php. The feature is a huge step forwards for WordPress as it moves closer to being a viable CMS solution (without all the hacks). There have been a number of projects I’ve worked on that have required a custom post type; rather than relying on the client selecting the correct category under ‘Add new post’, which tends to always leads to issues.

I’m in the process of converting nooshu.com to use custom post types and taxonomies, the main area in particular is my portfolio section. At the moment the portfolio posts are just standard posts which have a category of ‘portfolio’ attached to them. It works, but I don’t get that warm fuzzy feeling, and it feels like a bit of a hack. So time to start using a custom post type of ‘portfolio’ (yay!).

Unfortunately at the moment there doesn’t seem to be a quick way of converting a published standard post into a shiny new custom post type, at least not from the administration area. After a little investigation work using phpmyadmin and the nooshu WordPress database, I discovered it’s actually quite easy. Be warned though, it’s easy to break your blog by editing the database directly, so make sure you back everything up. I take no responsibility for what happens if you break something!

To convert a post into a custom post type; in phpmyadmin look for the wp_posts table. Inside it do a search, where the ‘post_type’ value equals ‘post’. This will give you a list of all your posts (otherwise you will also have all the revisions and attachments listed). From the list you should be able to pick out the posts you want converting to your new post type, edit one of these posts and change ‘post_type’ from ‘post’ to your new custom post. In my case this would be ‘portfolio’:

phpmyadmin admin panel for a WordPress post

Change 'post_type' from 'post' to your custom post type.

Click save and go back to the previous page. Done! You should now see the post appear under your new custom post type in the WordPress admin panel. If you have any issues just change ‘post_type’ back to ‘post’ and it will reappear under the standard posts. No information is lost when changing the post type.

It’s not an ideal solution, hopefully it will be possible to do it from the administration panel in the future; but it does save having to re-enter all the posts under the custom post type for the moment.

WordPress 3.0 RC1 blank page error

Update: Apologies to the author of Hyper Cache, the error isn’t cause by the plug-in. The error is being caused by DB Cache Reloaded. After updating the site to 3.0 final I was getting the error on the update page, disabling DB Cache Reloaded fixed it.

Update 2: DB Cache Reloaded has now been updated and works flawlessly in 3.0, get it here.

I’ve been eagerly awaiting the release of WordPress 3.0 (due any day now!). I plan on making a few changes to my blog once it is released so decided to try out Release Candidate 1 on my development server. At first it all went fine, upgraded the database no problem… then a blank page. Weird! After a couple of page reloads the sparkly new dashboard popped up (it’s not that different, although it does look greyer). Clicking around the admin area I could see this blank page error was randomly occurring on different pages; bugger!

My immediate thought was a plug-in I had installed, as I’m sure this rather large error would have been picked up while testing the WordPress core functionality! Looking at my Apache error log the following error was listed:

1
[error] [client 127.0.0.1] PHP Fatal error:  Call to undefined method wpdb::get_blog_prefix() in dev.nooshu.com\\trunk\\httpdocs\\wp-admin\\includes\\user.php on line 260, referer: http://dev.nooshu.com/wp-admin/edit.php?post_type=portfolio

The error is too vague to actually help, but after a little investigating (and from a hunch I had) I disabled any plug-ins involved in page caching; namely DB Cache Reloaded and Hyper Cache. Unfortunately disabling them still didn’t fix the error, so I decided to remove them completely (db-config.ini, advanced-cache.php and db.php removed from the wp-content directory). Suddenly no more blank page errors occurring! Huzzah!

So if you come across the same problem, then check what caching plug-ins you have installed. When 3.0 final is released I’ll be doing a fresh install of both plug-ins. Hopefully that will solve the issue. They are both quite popular plug-ins so I’m sure others have had the same issue.

NextGEN Gallery + WordPress custom fields = happy developer

Over the past couple of weeks I’ve been working on a number of WordPress projects, all of which have needed some basic photo gallery functionality. As I’ve mentioned before in previous posts, NextGEN gallery is my WordPress gallery of choice, there really is nothing that comes close to it in terms of features and customisation (that I know of, if there are others post a comment!).

To add a gallery (or album) to a post / page is as simple as adding ‘[ nggallery id=x ]‘ to the post content… super! One issue though… what happens when you allow a client to edit and add new pages; well what usually happens is the tag gets deleted or changed, the gallery breaks, client panics and the virtual world ends (well not quite, but close). A technique I have been using to help solve this issue involves using WordPress custom fields and the excellent Get custom field values plug-in. You can grab the custom field values directly from WordPress using get_post_meta() but the plug-in makes it much easier.

Digging through the nggfunctions.php file in the NextGEN gallery plug-in folder reveals a whole host of useful functions that can be easily called directly from inside your WordPress theme. So say you wanted a gallery in a post page, but didn’t want the client to have to remember ‘[ nggallery id=x ]‘ every time, simply add this code next to your content in the single.php file:

1
2
3
4
5
6
<?php
    if(c2c_get_current_custom('galleryID') != ''):
        $gID = c2c_get_current_custom('galleryID');
        echo nggShowGallery($gID);
    endif;
?>

Add a custom field of galleryID with an integer value linking to the relevant gallery and you’re done. Now the client can pick out the galleryID custom field from a drop-down since WordPress remembers the custom fields used. Much easier for a client to remember than adding the tag every time.

I highly recommend looking through the nggfunctions.php file, here are just a few functions that are available:

  • nggShowAlbum(): Show a whole album depending on the ID.
  • nggSinglePicture(): Show a single picture from an ID.
  • nggShowRandomRecent(): Show random image(s) from a certain gallery.
  • nggShowSlideshow(): Show a flash slideshow pulling images from a specified gallery.

I have used nggShowRandomRecent() quite a few times in the past few months, here’s a quick example:

1
2
3
4
5
<?php
    //Show 6 random images using 'my-template' from gallery 4
    //(order, number of images, template, gallery ID)
    echo nggShowRandomRecent('random', 6, 'my-template', 4);
?>

Pick 6 images at random from a selected gallery on page load, very simple and effective.

Note: When using the random images function make sure you don’t have any WordPress caching plug-ins running on the selected page, else it won’t work as the page gets cached on first load. It took me a good 15 minutes to figure out why the function had suddenly stopped working due to this slight oversight.

CodeColorer Auto Expanding Code

Just quick post on a small feature I’ve just added to the site which I thought I’d share. It’s a slight addition to the CodeColourer plug-in for WordPress. CodeColourer formats and colourises code blocks in your blog posts for better readability. It comes with several different styles built in, or you can customise it using your own CSS file.

A feature that I saw on another site (although I can’t remember which) was when a user rolled over a code box it would expand to fit the code, allowing the user to see everything. Cool little addition, so I decided to create my own using jQuery. I’ve taken some of the code from the plug-in and pasted it below so you can see it in action:

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
if($(".codecolorer-container").length){
    var $code = $(".codecolorer-container").each(function(){
        var $this = $(this);
       
        //Animation decision object
        var decisionObject = {
            w: false,
            h: false
        };
       
        //Original width / height of the displayed code
        var originalWidth = $this.width();
        var originalHeight = $this.height();
       
        //Width / height of hidden portion of code
        var mainWidth = $this.find(".codecolorer").width();
        var mainHeight = $this.find(".codecolorer").height();
        var lineWidth = $this.find(".line-numbers").width();
       
        //Only attach events if needed (ie has scroll bars)
        if((mainWidth + lineWidth) > originalWidth || mainHeight > originalHeight){
            /* and so on...... */
        }
    }
}

Since this action is fired on hover, I didn’t want the code boxes expanding immediately every time a user hovers over a box; as just scrolling down the page would expand the boxes which would become extremely annoying. The boxes should only expand when the cursor is left over the box; lucky there’s a plug-in for jQuery that already adds this functionality, it’s called $.event.special.hover.

Special hover simply replaces the standard hover event with one that monitors the speed of the cursor over a set period of time. If the cursor speed drops below the threshold the hover event fires. This is enough to stop random hover events firing when a user navigates over the page, simple!

I’d be interested to see if the code works for others using CodeColorer, there’s no reason why it shouldn’t. Download the code, give it a try and let me know what you think.

WordPress plug-in: Post Thesaurus

Over the past few days I’ve been working on a new WordPress plug-in, one that I personally have desperately needed recently. It’s called ‘Post Thesaurus’ and it does exactly what you’d expect it to do. It creates a little widget on the side of the ‘Add new post’ page which you can use to suggest new words of the same meaning.

After finding I use the word ‘great’ a little too much, I thought it was about time to do something about it. Here are a few screenshots of the plug-in in action:

Post Thesaurus before I've searched for a set of words.

Notice the widget in the top right corner.

Post Thesaurus after I've completed a word search

The widget has completed a search and populated the results panel.

Big thank you to Big Huge Labs for providing the excellent API. I’ve included an admin page with a few settings (under ‘settings’). One feature to note is the ability to enter your own API key. I’ve added this just in case the plug-in starts exceeding the 10,000 requests per day a single API key is allowed. Sign up is simple and only takes a couple of minutes, then you’ll have 10,000 requests per day all to yourself.

I’ve implemented the API using a little jQuery Ajax goodness and some JSONP. Since jQuery is used by the WordPress admin by default, there’s no additional overhead in having to add it manually.

Grab the plug-in off the WordPress site here, or you can download the zip from my site here (Version 1.0.0.0).

Hope you find it useful, any feature requests or bugs leave a comment below.

Currently on page 3 of 512345