Archive for the ‘Bug Fixes’ category

Help! Help! My [X] doesn’t work! – How to sort out basic WordPress issues and getting to the cause of a problem without the need to panic

January 17th, 2013

broken-linkHappy new year! About this time of year clients come out of the woodwork after a lovely Christmas and with a renewed enthusiasm in their business and sites. So the first thing they do is mush the big Upgrade button within WordPress and upgrade their site core, theme and/or plugins. And then what happens? Well… nothing as it turns out because inevitably the last time they upgraded was a year ago and someone else did it and he’s gone on sabbatical to Jupiter and taken all of the backups with him and the company who wrote the site have gone bust and you might have been hacked a few times since then but a bloke from the pub sorted it out.. and so on.

So when you have the white screen of death (WSOD) or PHP errors all over the site what do you do? Well..

» Read more: Help! Help! My [X] doesn’t work! – How to sort out basic WordPress issues and getting to the cause of a problem without the need to panic

WordPress Page Excludes plugin support for Custom Post Types

September 11th, 2012

I have been using the Exclude Pages plugin for WordPress by simonwheatley for a couple of years. It was invaluable before the new wp_nav_menu stuff arrived and now I don’t use it so much but a few of my clients still do. The thing it doesn’t support out of the box is custom post types.

A client of mine uses the Optimizepress theme with the footer menu turned on and it will show all pages on the site unless they are excluded. This plugin works wonderfully for Optimizepress and i’m sure others normally until you add a custom post type and then it outputs that in the page menu as well. This plugin is wired nicely to work with custom post types but the meta box isn’t present in the edit pages. the following code snippet, when added to your functions.php file, will add it for the stated post type.. in this case ‘leads’

function sbep_admin_init() {
	add_meta_box('sb_ep_admin_meta_box', __( 'Exclude Pages', EP_TD ), 'ep_admin_sidebar_wp25', 'leads', 'side', 'low');
}

add_action( 'admin_init', 'sbep_admin_init' );

WP Ecommerce custom email content

March 6th, 2012

The WP Ecommerce system itself is a huge pain in the backside to use and work at times as we all know but a nice saving grace is that the plugin has a huge range of hooks and filters which we, as developers, can write plugins and blocks of code to extend.

My latest issue has been the checkout fields system. I am told by one of their staff that it’s due a rewrite in future versions however for those using older versions… You might notice that it’s not the simplest system in the world. Don’t get me wrong it’s my shopping cart of choice but I think there are a few areas where a little work could polish it up nicely. Checkout fields define what questions are asked of the buyer on the checkout page. Default values include their billing and shipping address but it’s not uncommon to want to add fields of our own to that like newsletter signup for instance. A project I am working on at the moment has a pickup point field present which we want to add to the user or admin emails. The ‘shortcodes’ provided are limited but luckily the filter ‘wpsc_transaction_result_message’ (and a couple of others) allows us to hook into it and run our own code as follows:

add_filter('wpsc_transaction_result_message', 'sb_transaction_results_custom_fields');
add_filter('wpsc_transaction_result_report', 'sb_transaction_results_custom_fields');
add_filter('wpsc_transaction_result_message_html', 'sb_transaction_results_custom_fields_html');

function sb_transaction_results_custom_fields_html($message) {
return sb_transaction_results_custom_fields($message, true);
}

function sb_transaction_results_custom_fields($message, $html=false) {
$values = array();

foreach ($_SESSION['wpsc_checkout_saved_values'] as $key=>$value) {
if ($value) {
if (is_array($value)) {
$value = implode(', ', $value);
}

$values[] = $key . ': ' . $value;
}
}

$message = str_replace('%custom_fields%', implode(($html ? '<br />':"\n"), $values), $message);

return $message;
}

These functions will replace the new shortcode %custom_fields% with the entire contents of the checkout form. It’s not pretty in this form which is why we should use the ID and then reference the field name in the database when making it into a plugin. I might do at some point but for now it’s a handy little bit of reference code for people to work with. I am happy to explain more if anyone if interested.

Terminal takes an age to load on my Mac? The solution

February 16th, 2012

This has been bugging me for months… whenever I opened up the Terminal App on my iMac it took a good 30 seconds to do anything. I only just now, whilst waiting for it to load, bothered to Google the answer. Apparently it makes use the asl directory underneath /private/var/log. ASL is an acronym for Apple System Log and relates to one of a whole raft of system related logging. These logs can safely be cleared although it might be worth taking a backup just in case.

Running the following code will, in effect, delete the contents of that directory and all things using that directory in a reading capacity (working with the logs as opposed to writing their own) should speed up.

sudo rm -f /private/var/log/asl/*.asl

Note that this is non recoverable, hence my suggestion you take a backup first. Hope it helps someone else like it did me!

WordPress SB Mail Attachment Widget Update (V1.1)

January 31st, 2012

A minor update today to improve the delivery efficiency of the emails with attachments. If you have no idea what this plugin is then check out my original post on it a few weeks ago here.

Some users were reporting issues with the email coming through as ignoring the HTTP headers and including all of them within the email itself. A big mess indeed. Now it uses the wp_mail command so it can be hooked into by other plugins. Also because of this function usage it means that I don’t need to write the headers manually.. WordPress does all that for you. It should now be a lot more compatible with the various mail clients.

Download it here: SB Mail Attachment Widget (2.81 kB)

How to fix the flaw in the WP Ecommerce table rate shipping module

January 25th, 2012

Catchy title eh! It’s difficult to name such a post but I have just diagnosed a client’s site and realised that there was a bit of an error in the WPEC (WPSC) table rate shipping module.

Reading the code it looks like the table rate module is designed to be used exclusively or in conjunction with a secondary service. The flaw I have found is that table rate is coded to always return a price regardless of whether you want one or not.

Basically my client wanted to use the weight shipping module for all postage except if the cart amount was more than £200 in which case free postage would be offered. Simple right?.. just add a layer (row) into the table rate settings with a minimum price of 200 and a value of 0. This would mean that weight based is used until the table rate conditional kicks in at £200 and offers cheaper postage (free in fact).

No.. sadly not correct :(

Table rate is written so that is always returns a price regardless of whether you want it to or not. Basically if you have a single row (layer) in the settings for the module it will show it. The system works well at the top end where price is greater than or equal to but there must always be a base price in the module (value of 0.00 or 0.01 if it doesn’t save) to catch those which fail the PHP logic. Note the following function to get a quote (taken directly from tablerate.php):

    function getQuote() {

        global $wpdb, $wpsc_cart;
        if (isset($_SESSION['nzshpcrt_cart'])) {
            $shopping_cart = $_SESSION['nzshpcrt_cart'];
        }
        if (is_object($wpsc_cart)) {
            $price = $wpsc_cart->calculate_subtotal(true);
        }

        $layers = get_option('table_rate_layers');

        if ($layers != '') {

            // At some point we should probably remove this as the sorting should be
            // done when we save the data to the database. But need to leave it here
            // for people who have non-sorted settings in their database
            krsort($layers);

            foreach ($layers as $key => $shipping) {

                if ($price >= (float)$key) {

                    if (stristr($shipping, '%')) {

                        // Shipping should be a % of the cart total
                        $shipping = str_replace('%', '', $shipping);
                        $shipping_amount = $price * ( $shipping / 100 );

                    } else {

                        // Shipping is an absolute value
                        $shipping_amount = $shipping;

                    }

                    return array("Table Rate"=>$shipping_amount);

                }

            }

            $shipping = array_shift($layers);

            if (stristr($shipping, '%')) {
                $shipping = str_replace('%', '', $shipping);
                $shipping_amount = $price * ( $shipping / 100 );
            } else {
                $shipping_amount = $shipping;
            }

            return array("Table Rate"=>$shipping_amount);

        }
    }

If you read through the code it basically loops through all of the layers to find the conditional price point that matches and returns the price. The oddity is the next set of code which, I suppose, is a fall back. Sadly the fall back is entirely unnecessary and causes this issue. The code starts from the following onwards:

$shipping = array_shift($layers);

In fact the simplest way to ‘fix’ the function is to put a return  statement just before that line:

return false;
$shipping = array_shift($layers);

Once that is in place you are free to use the module properly once again. I might write this as a separate shipping module for people to download as changing the name of each layer would be a nice idea as well as setting a maximum price point for each layer.

Turn off theme CSS for the visual editor in WordPress 3.3+

January 5th, 2012

It’s been on the cards for months and WordPress has finally added the inbuilt function whereby CSS files declared on the front end are now also declared on the edit item (post/page/custom post type) pages within the admin system. This is wonderful for some but, as someone who looks at a fair few sites using a range of free, premium and bespoke themes, actually it’s a curse in disguise. Let me explain…

Let’s say you go to the WordPress theme repository and grab a nice free theme which has been written by a developer less than ‘au fait’ with WordPress functionality or best practice. You turn on the theme, all looks good and then go to write a post only to be presented with the page from hell because loose CSS rules used in style.css have broken the editor page look and feel all together. As there is no way in CSS to set a priority without rewriting the code itself you are left with a mess.

Pre WordPress 3.3 this wasn’t an issue as you needed to explicitly declare an editor style sheet in order to use the styles and make it look somewhat closer to that which you might find on the front end of the site.

Now.. turning it off! Well it will require some coding and in actual fact the simplest way to do anything about it is to make your stylesheet invisible to WordPress. Let me explain: The correct way to enqueue any CSS and JS on your site is to do something like the following:

add_action('wp_print_styles', 'theme_add_stylesheet');
function theme_add_stylesheet() { 
    wp_register_style('theme_stylesheet', get_stylesheet_directory_uri() . '/style.css');
    wp_enqueue_style( 'theme_stylesheet');
}

This means that when the wp_head action is triggered from header.php in your theme the style will be printed to screen along with the other styles and scripts. The enqueue style function adds the name and location of the script to a global array which can be reused at any time. In short, WordPress knows that it is a CSS file declared by a plugin or theme and therefore can reuse it at will.

The fix is simple.. don’t use that method and, instead, use the original crude method of adding a stylesheet which is to write the HTML yourself as follows:

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />

This code, when placed in header.php of your theme, simply outputs the line in the head section of your page and includes the stylesheet unbeknown to WordPress and therefore won’t be used in the editor.

99% of the themes I have seen and used use the latter method so it’s not an issue but hopefully this will hel someone who has just upgraded and has some sort of multicoloured and wierdly laid out admin post page.

WordPress plugin queue jumping made easy

January 1st, 2012

Hi all. Happy new year etc.. I have plenty of plans for the next 12 months but won’t go into them unlike every other person with a blog is undoubtedly doing at the moment. I want to keep this strictly useful information and me telling you I want to shift some weight, buy something or do something isn’t going to improve your lives any really is it. So here goes..

I have had an interesting problem for some months now which I have just solved albeit crudely! I have written several plugins and released them into the WordPress plugin repository as regular readers of this site might already know. What you are unlikely to know though is that in doing so all you get is an influx of support questions. I personally like these.. it gives me the illusion of helping people out whilst really knowing that it should have been right to begin with :)

The worst of these aforementioned support questions are to do with plugin conflicts. Cue potential threads and threads about how the ‘other guy’ did something wrong which is going to need to poor user to go to their site/forum to get it sorted before our plugins can work in harmony as they were originally intended. This isn’t the best answer to a support question and certainly won’t get you any repeat custom. In all likelihood the user will ditch the plugin he finds least useful (yours.. after all he came to you to sort it in the first place meaning yours is likely the plugin they have just installed and are playing with) and install one of the other counterparts which undoubtedly does the same job but with umpteen donate buttons plastered all over it (I won’t go into that one right now but see my previous post for my thoughts on that particular subject).

One such example of a conflict I have been getting all year. It’s to do with my Welcome Email Editor plugin. WordPress does a fair few things very well indeed but sadly there are a few where it really could improve. This is why my Welcome Email Editor plugin exists at all. Can you guess what it does? Really? Ok so it lets you edit the WordPress welcome email.. the one that gives the user their user name and password if they decide to sign up for your site. The default offering is a little dull but luckily the guys who wrote WordPress have half heartedly thought about how it can be improved. Why let plugin writers like me do it of course. Sadly they opted not to use the action and filter system which already is ingrained in the rest of WordPress (for good reason I’m sure.. likely to do with load order) but instead just wrapped the entire wp_new_user_notification function in a PHP function called function_exists. This does what it says on the tin and only declares the function if someone else (a plugin or theme) doesn’t get there first.

In most cases this system works fine when you install a plugin dedicated to editing the welcome email and leave it at that. In reality most blogs have 30+ plugins active at any one time and probability and inevitability both say that more than one person is likely to want to jump on this handy feature for their plugin or theme. This means that one of the plugins needs to go! Normally if it were two plugins designed to edit the welcome email then we would be ok.. an obvious conflict of interest but what if one were a forum or shopping cart in conjunction with my plugin? Which goes then? Well the one which provides less functionality of course which, sadly, in that example would be my little plugin.

To make it somewhat more awkward, some plugins like to call WordPress core files directly thus causing the default function for the welcome email to be called before any other plugins and therefore chucking everyone else out of the race to declare the function first. Maintenance Mode is a plugin I know which does this when the system is active although it sorts itself out when you come out of maintenance mode so not really an issue. I have just been informed of another conflict with a plugin which makes dealing with WP Ecommerce in bulk easier (and we all know that was needed years ago!). Whatever reason they have called pluggable.php for I don’t know but it means that my plugin (or any other trying to declare a function first like this (it’s more common than you think!)) won’t function.

It’s such a simple solution but it works.. to fix you just need to rename my plugin directory to something else. WordPress naming conventions make calling a plugin anything starting with ‘WP’ very trendy indeed. My plugins are all prefixed SB, my initial, for archiving more than anything else but the people who do the same with initials AA are laughing at us all right now I assure you (or not laughing but living in blissful ignorance!). Here’s the logic.. it’s really simple:

On any given page load WordPress will load it’s core files first and then look for plugins to bolt on to the system using the action/filter system. This is where the PHP files are initially ‘required’/'included’ and individual balls (controlled by the plugin writers) set in motion. WordPress keeps a list of active plugins to call in the database in the wp_options table under an imaginatively named row called ‘active_plugins’. This is an alphabetically ordered list of plugins labelled by their location beneath the plugins directory (eg: welcome-email-editor/sb_welcome_email_editor.php). It will run from top to bottom including these files. This means there is a priority order for code defined only by the fact it has a name higher up the alphabet.

So to conclude the way to get your plugin run first to avoid conflicts with other plugins just put it in a directory called something beginning with a low alphabetical letter or special character. In my case I get a conflict every few months so it’s not worth changing but I am going to recommend that the next person to mention a conflict just renames their plugin folder from welcome-email-editor to -welcome-email-editor (note the leading hyphen). Job done!

I might add that changing the name of a plugin directory once a site is live isn’t a good idea on account of some plugins storing pathing information in the DB and WordPress itself storing the fact that plugin is active or not by it’s name in the directory tree. Put plainly if I change the name of my Welcome Email Editor plugin on my own site then it will deactivate itself and I shall need to reactivate it for it to continue working. Not a huge feat but try explaining that to normal user. Cue yet more support emails.

Hope this explains an issue for one or two of you. Perhaps plugin writers will learn not to call core PHP files directly in future to make my day run more smoothly… I doubt it!