Git stash

I use Git when working on my WordPress projects.

On occasion, when I’m working on the latest branch and testing out some changes, styling, code etc, I’m *really* excited that I’ve squashed that bug / made that visual improvement.
However, it’s only then that I realize I didn’t create a new branch for my current round of changes.

So, it’s copy/paste, multiple CTRL-Z’s and then paste in. But wait! The changes are in multiple files. Darn.

Have no fear. Git can help.

At the command line:

git stash
git stash branch new-fix-feature-branch-name-you-should-have-created-in-the-first-place

Git stashes the original changes, then creates and checks out the new branch name I provide and places me in the new branch *and* applies the changes.

The changes that were stashed and then applied to the new branch are also removed from the “stash pile” by design and upon successful application.

And Voila! Sanity replaces profanity.

WordPress plugin – Featured Image Admin Thumb

I am happy to share my latest WordPress plugin.

Inspired by a recent site I was working on, this plugin helps identify the featured image that is associated with each Post or  Page.

Find out more about the plugin and try it out for yourself.

Featured Image Admin Thumb – WordPress plugin

*Update* – this plugin is now hosted, updated and available from the WordPress plugin directory – here’s the link to Featured Image Admin Thumb on the directory.

** Double update ** – I’ve added more features to this plugin and the latest version is now available.

WordPress Backups

Backups. Everybody talks about them and says they are doing them, or going to do them or definitely going to do them. However, sometimes the truth is no backup is in place. I wanted to raise awareness and encourage backups for WordPress site owners by describing one of the backup options in the WordPress field.

WordPress backup with PressBackup and Amazon S3

Talking at the Chicago Northside WordPress meetup on Updates, Backups and maintenance I described how you could configure a WordPress backup solution, PressBackup, to work with Amazon S3. By using Amazon S3 you get the benefit of  potentially unlimited backup file storage for free (12 months initially) or for relatively low cost. You create an account with PressBackup and then you can use your Amazon account by adding the S3 service (a few sign up steps), retrieve the Amazon security and authentication keys and put them into PressBackup and then the backups can begin.

I also noted that PressBackup can work with DropBox (free/paid) and there is also a PressBackup storage service (paid).

Each site is different and there are quite a few factors to consider when planning your backup strategy. At the meetup we also discussed having a confident recovery strategy in place and considered that as important as backing up in the first place. Whilst PressBackup is not fully automatic in recovery it does backup and organize the plugins, themes, uploads folder and makes them easy to extract from the backup zip file.

Take a look at the slides from my WordPress backups presentation below.

 

Add a bit of style to the WordPress categories widget

By default the WordPress categories widget offers quick and easy links to your content categories. With a little bit of CSS you can easily make some stylish additions to the output.

So, here’s the before shot:

categories-before

But in this case I want to add little style, some graphics or perhaps some Font Awesome – something like ” ” (quotes at the beginning or end) or &raquo suffixes to the category links. Now, sometimes you can add some filter code (requires programming knowledge) that works with widgets to modify the output but with the Categories widget  the only amendment you can make is to exclude select categories. The default categories widget doesn’t offer content or style changes in that way so we’re pretty much stuck with its default output.

If you wanted to you can clone the default categories widget code (requires programming knowledge), include it in your theme and make modifications – perhaps just adding the extra character – and you then have the choice of widgets to use.

However, there’s a slightly easier way that only requires the ability to add some CSS to your theme (requires no programming knowledge) and you can make these small style changes changes. For this example I am showing you some code that will add a quote around the category name and » to the end of your category name.

The categories widget outputs the categories in an block like this:

<li class="cat-item"><a href="/category/bananas">Bananas</a></li>
<li class="cat-item"><a href="/category/apples">Apples</a></li>

We will hook into the cat-item class and use CSS psuedo elements (including legacy browser support) and add the code for raquo, “00BB” into the :after element.

.cat-item {
    *zoom: expression(
    this.runtimeStyle.zoom="1",
    this.appendChild( document.createElement("small") ).className="after"
    );
}
.cat-item {
/** Any other specific cat-item styling can go here */
}

.cat-item .before,
.cat-item:before {
        content: '\201c'; /** Open quote **/
}
.cat-item .after,  /* IE6/7 */
.cat-item:after {
    content: '\201d\00BB'; /** Close quote and brackets */
}

And here’s the after shot:

categories-after-01

So with a small bit of CSS and no programming you can easily add many embellishments to your categories or in fact any other list. And you can get fancier with your CSS by playing a little more perhaps with inspiration from http://css-tricks.com/

Legacy support code – thank you: http://richard.parnaby-king.co.uk/2012/07/pseudo-classes-before-and-after-in-ie6-7/

WordPress issue – ‘blog pages show at most’ not working

While working on a client project I thought it would be best to use real content from the clients site to check, amongst other things, if pagination was working on the home page.

After importing the clients data into my development site I refreshed the the home page and looked for pagination at around 10 posts (the default).

Not so – the home page filled up with posts and right at the bottom was my post navigation – older / newer posts links.

I visited the WordPress Settings, Reading page and changed the “blog pages show at most” settings to a different number and refreshed the page.

Again nothing changed.

This time I search to see if this was a known issue (can’t think why it would), I checked my index.php code and compared to other theme files, I switched to the default WordPress theme and still the homepage filled up with posts.

Finally after more searching I came up with the solution – sticky posts.

It was then that I realized that all the posts in the client data (over 300) were set to sticky.

That’s why the pagination wasn’t working.

Now, in the WordPress Admin Dashboard I’ll have to uncheck “Make this post sticky” for each post or (perhaps a little faster) manually change one option in my wp_options table to changes the sticky settings.

If you are comfortable messing with your WordPress database you can reset the ‘sticky_posts’ option in the wp_options table. I made the following change to the ‘sticky_posts’ field in my development database. I edited it to be “a:0:{}” and all the sticky posts were gone!

A simple solution to cap off some head scratching and I hope this helps you out if you encounter the same issue.

Post comments not allowed if comment metabox removed

Allow Comments in edit post

When building a site for clients it’s nice to clean out the Admin Dashboard screen of some of the unnecessary (and possibly dangerous) sections and checkboxes to avoid distractions when creating or editing their content. WordPress is flexible enough to allow sections, or meta boxes, to be easily removed through the use of the remove_meta_box function. The code can be added to the functions.php file.

One of the meta boxes that can be removed is the Comments or Discussion meta box. This box lives in the lower half of the Edit post screen. It allows you to set the post, or page, to accept or deny comments and trackbacks/pings. I’ve been working on a couple of sites for some clients and it was originally decided not to have comments at the launch. I removed the comments options from the post screen and removed the call to the comment template in the sites theme files.

Then the client changed their mind and would like comment functionality restored. Now, it’s some time into the life of the site and the previously created posts are showing that comments are closed and the client want to add the ability for all posts to allow comments. It is easy to edit the theme files and add back in the “comment_template()” code and that would be that. However, the posts still show “Comments are closed”.

In Settings, Discussion there are no restrictions for commenting so it’s a little confusing that comments are not showing.

After working a little further on this I found the trick, which can be a little time consuming if you have lots of posts. Either edit, or quick edit, each affected post and tick the box that says “Allow Comments”.

Allow Comments in edit post
Allow Comments in edit post

After doing that for each post you should find that normal comment functionality is restored for all posts and for new projects I always try and identify the comment requirements at the outset.

Slow WordPress tag queries

While working on a real estate project I encountered very slow response from WordPress on certain queries. These queries are multiple tag queries in the form:

http://www.site.com/tag/TAG_ONE+TAG_TWO

My application is using WordPress tags to annotate the content and I am providing links to those multiple tag queries throughout the site. Over time and while I was developing the site I noticed the site response getting slower and slower when I clicked on these links and yet there are times when the response was within the acceptable range. My hosting service was also affected and I was seeing high CPU usage when one of these queries was triggered. I decided to investigate.

I bounced between my Apache configuration, my MySQL configuration and the external database I was also querying. I had used the external database in a previous project and I was fairly confident I had not introduced any issues there. The queries I was performing were responding well within acceptable times and using mtop on my hosting console I was seeing WordPress queries hogging the resources.MySQL query

I changed the settings in my MySQL configuration file to increase buffers, heaps, table sizes and more. Improvements were minimal where there were any and in other cases no change. I didn’t think I was doing anything beyond the scope of WordPress (although I always like to learn) so I started searching to see if anyone else was experiencing the same or similar issues.

I found the usual and variable guides on how to speed up WordPress and more about taxonomy queries. I found there were reports of issues after a recent WordPress upgrade – support questions were posted here and here.

Digging deeper I did come across a WordPress Trac ticket http://core.trac.wordpress.org/ticket/16706 and that seemed to be very similar to my issue.  I have been keeping my installations up to date so I could see that I became affected at that same upgrade point. Reading the Trac ticket it seems a resolution to this issue is due in the next release of WordPress (3.2) but I wanted to find out if it really did fix my issue. I upgraded my site to 3.2 beta and applied the patch mentioned in the ticket. The difference is huge and the site response time is much closer to where it should be.

Reading through the Trac ticket the explanation of the issue and the fix is purely down to optimization of the query built when WordPress is required to display information based on multiple categories or tags.

**UPDATE**: It seems that these multi tag queries are operating efficiently after upgrading to WordPress 3.2+ and this hint/tip might no longer be valid or required.

Importing data into WordPress

WordPress Import Real Estate Listings

I’ve been working on a project that requires me to reference an external database of property listings – 106,000 of them – and display these listings in WordPress.

One way I thought of was to create a plugin to read the listing data into WordPress, create a post and custom meta fields (or even a custom post type) with all that listing information and then categorize / tag each post allowing themes to organize the listings as needed. I reviewed that idea didn’t think it was necessary to duplicate the real estate listing data in the WordPress database.

But, if I could create posts with ids that match the listing id then with the help of a shortcode, I could create posts and the shortcode would pull the listing data when a post is viewed.WordPress Import Real Estate Listings

I thought it would work so I reviewed the wp_insert_post function in the Codex and found it had a parameter “import_id”. Now, if I could make that import_id match the real estate listing id I could easily use the categorization and tagging capabilities of WordPress to organize the posts. When populating the WordPress site I query for and retrieve the listing ids from the database, get the id and create the post. Then, just after the post creation process I further query the listings database and create the categories and tags I need assigning them to each post id.

With all the listings referenced in WordPress I can search on and display posts by category and tag or include some external searching capability to get the IDs I want and then use WordPress to display the listings that matched the search.

For the purposes of the project this method worked, but with one side effect. All the menus, pages and other WordPress elements are numbered like the posts. So, at some point, there may be a clash between a numbered menu item and a real estate listing with the same id but I’ve yet to hit it.

Adding Child Theme filters and Twenty Ten

Working on a child theme project for a client I found that my filter modifications for both ‘excerpt_length’ and ‘excerpt_more” were not being processed. My child theme is based on Twenty Ten and the filters I was using had already been filtered by the parent theme. So, I had added my custom filters and the Twenty Ten filter removal code to my child themes functions.php.

However, these custom filters were not being actioned. To help me debug what was happening I even added PHP error logging to check the return values from the remove_filter functions and that proved the filters were not being removed prior to mine being added but I still couldn’t work out why.

Finally by searching the WordPress forums I came across this post and read the reply from lordarkad. It made sense. In my child theme I had to wait for the parent themes setup to finish before declaring my filter changes and this made more sense because the child themes functions.php is loaded prior to the parent themes functions.php. So whilst these filters showed in the parent theme code I was removing them before they had been applied and, of course, then the parent themes functions.php was applying it’s filters in the theme.

To fix it I followed lordarkad‘s comments and created my filter additions in a child theme setup function. Then I added that function to the “after_setup_theme” action so my function is called after the parent theme has complete setup and then my filters are applied correctly.

This is a snippet of what I ended up with:

add_action( 'after_setup_theme', 'mytheme_theme_setup' );

function mytheme_theme_setup() {
	if (!function_exists('mytheme_new_excerpt_length') ) {
		function mytheme_new_excerpt_length( $length ) {
			return 20;
		}
	}
	remove_filter( 'excerpt_length', 'twentyten_excerpt_length' );
	add_filter( 'excerpt_length', 'mytheme_new_excerpt_length' );
etc...
} // end of mytheme_theme_setup

WordPress 3.0 and flush_rewrite_rules

I thought I would document this experience I had when upgrading some sites to WordPress 3.0.

After WordPress 3.0 came out I took some time to upgrade blogs I manage and was impressed how well the upgrades fared. No issues, fair warnings and ultimately upgraded sites. However, on one of my development sites, after the upgrade, I noted an error about “error re-declaring the function flush_rewrite_rules()”. I knew, for this site in particular, that I had written some custom code to rewrite the urls and in this case I had innocently included a function called “flush_rewrite_rules()”. Coincidentally, in WordPress 3.0 a new core function has been created called “flush_rewrite_rules()” and because that now exists my function is interfering with this and required fixing. The fix, in this case was to rename my custom function and test and I thought nothing more of it. (I know – I should have participated in the beta test).

I didn’t think anything of it after that until I was asked to assist with another clients site. This time the client had innocently upgraded their site to WordPress 3.0 and encountered a white screen with the long PHP error referencing “error re-declaring the function  flush_rewrite_rules()”. The difference this time was that it was in a plugin causing the issue and as such the site was rendered inaccessible.

For this client I connected via FTP and downloaded the plugin code, searched for the function named  “flush_rewrite_rules()” (along with any references to it) and renamed it through the code. After uploading the change the site was restored back to normal.

A simple fix for this site but also a simple lesson in heeding the warnings / suggestions given by the WordPress upgrade tool when upgrading to WordPress 3.0