Tag Archives: coding

Air is a full-featured Plogger 3 stand alone theme that takes visual cues from the Yahoo! TV beta of mid 2007. The theme files validate as XHTML 1.0 Strict (while Plogger itself is either Strict or Transitional, depending on some options). The theme looks nearly identical in Firefox 2.0 and Internet Explorer 7, and uses conditional CSS to be very similar in IE6. A version of this theme is included in the official Plogger 3 build, released on 7/10/07.

Plogger beta 3 theme: Air screenshot

The fundamental changes are:

  • The theme template files are now primarily HTML with some PHP, rather than being entirely written in PHP. This will make it easier for people with basic knowledge of HTML to further customize the theme.
  • The compatibility with Internet Explorer 7 has been greatly improved. Among other things, a new float and clear bug introduced in IE 7 has been avoided. The theme is inherently much more stable and less prone to breaking in different browsers.

Note that this theme is only for use with Plogger 3. If you’re using an earlier version, it’s recommended that you upgrade.

Download the stable version (v0.1)

Download the latest stable version of the Plogger 3 Air theme here. Because I tend to tinker with things, the files here will probably be slightly more up-to-date than those bundled with the full Plogger download.

Download the “Air” Plogger 3 theme

Download the beta version (v0.2 beta)

If you don’t mind the occasional bug or glitch, download the beta version to get a look at some new features. The album view in v0.2 beta supports centered thumbnails and can be set to display each picture’s date when no description exists – take a look at album.php for commented instructions. I’ve posted some documentation regarding the method for centering the thumbnails at Centering the thumbnails in Plogger. The code should work for any fixed-width theme derived from the default, but the method could be adapted to center many other layouts that use floated list items instead of tables.

Download the “Air” Plogger 3 theme – beta

The WordPress function wp_get_archives(‘type=postbypost’) displays a lovely list of posts, but won’t show the date of each post. This plugin adds each post’s date to those ‘postbypost’ lists, like so:

Add dates to wp_get_archives

Add dates to wp_get_archives

Usage

  1. Upload and activate the plugin
  2. Edit your theme, replacing wp_get_archives('type=postbypost') with if (function_exists('ard_get_archives')) ard_get_archives();

The function ard_get_archives(); replaces wp_get_archives('type=postbypost'), meaning you don’t need to specify type=postbypost. You can use all of the wp_get_archives() parameters except ‘type’ and ‘show_post_count’ (limit, format, before, and after). In addition, there’s a new parameter: show_post_date, that you can use to hide the date, but the plugin will show the date by default.

show_post_date
(boolean) Display date of posts in an archive (1 – true) or do not (0 – false). For use with ard_get_archives(). Defaults to 1 (true).

Customizing the date

By default, the plugin displays the date as “(MM/DD/YYYY)”, but you can change this to use any standard PHP date characters by editing the plugin at the line:

$arc_date = date('m/d/Y', strtotime($arcresult->post_date));  // new

The date is wrapped in tags, so you can style the date independently of the link.

How does it work?

The plugin replaces the ‘postbypost’ part of the function wp_get_archives, and adds the date to $before. The relevant code is below. You can compare it to the corresponding lines in general-template.php.

	} elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) {
		('alpha' == $type) ? $orderby = "post_title ASC " : $orderby = "post_date DESC ";
		$arcresults = $wpdb->get_results("SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit");
		if ( $arcresults ) {
			$beforebefore = $before;  // new
			foreach ( $arcresults as $arcresult ) {
				if ( $arcresult->post_date != '0000-00-00 00:00:00' ) {
					$url  = get_permalink($arcresult);
					$arc_title = $arcresult->post_title;
					$arc_date = date('m/d/Y', strtotime($arcresult->post_date));  // new
					if ( $show_post_date )  // new
						$before = $beforebefore . '<span class="recentdate">' . $arc_date . '</span>';  // new
					if ( $arc_title )
						$text = strip_tags(apply_filters('the_title', $arc_title));
					else
						$text = $arcresult->ID;
					echo get_archives_link($url, $text, $format, $before, $after);
				}
			}
		}
	}

The lines ending in ‘// new’ are the only changes.

So you want the date to appear after the title? Edit the plugin to modify $after, instead:

	} elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) {
		('alpha' == $type) ? $orderby = "post_title ASC " : $orderby = "post_date DESC ";
		$arcresults = $wpdb->get_results("SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit");
		if ( $arcresults ) {
			$afterafter = $after;  // new
			foreach ( $arcresults as $arcresult ) {
				if ( $arcresult->post_date != '0000-00-00 00:00:00' ) {
					$url  = get_permalink($arcresult);
					$arc_title = $arcresult->post_title;
					$arc_date = date('j F Y', strtotime($arcresult->post_date));  // new
					if ( $show_post_date )  // new
						$after = '&nbsp;(' . $arc_date . ')' . $afterafter;  // new
					if ( $arc_title )
						$text = strip_tags(apply_filters('the_title', $arc_title));
					else
						$text = $arcresult->ID;
					echo get_archives_link($url, $text, $format, $before, $after);
				}
			}
		}
	}

Download

Get the files here: (Current version: 0.1 beta)

Download the Ardamis DateMe WordPress Plugin

Update 7/31/10: I no longer support this plugin and have removed it from the site. You can still download the code, if you like, but it needs to be updated before it will work correctly.

This plugin allows you to add information from your Halo 3 Service Record to your WordPress blog.

The plugin displays your emblem, rank and grade, but with a little editing it could also display total the total number of games played, the date and time of the last game played, and any other information on the Halo 3 Service Record page at Bungie.net.

Installation

The download includes:

  • ardamis-halo3.php (put this in your /plugins/ directory)
  • halo3stats.css (copy and paste the contents into your theme’s style.css)

The plugin attempts to create a text file (halo3_cache_YOURTAG.txt) for use as a cache in your blog’s root folder automatically. Some server configurations may not permit the plugin to create this file and you’ll see resultant errors; in this case, you may have to manually create a file with that name and upload it to your blog’s root (and perhaps set permissions).

Usage

The plugin accepts one argument: your gamertag.

Insert the code:

<?php if (function_exists('ardamis_halo3')) ardamis_halo3('YOURTAG'); ?>

into a template file wherever you want the Service Record to appear, replacing YOURTAG with your actual Xbox Live gamertag, ex.:

<?php if (function_exists('ardamis_halo3')) ardamis_halo3('ardamis'); ?>

Download

Get the files here: (Current version: 1.0 beta)

Download the Halo 3 WordPress Plugin

How can I add the Service Record to a post?

Thanks to a really neat plugin, The Execution of All Things, you can call functions from any activated plugin from within a post. Once you have both the Halo 3 Service Record plugin and the wp-exec plugin installed, you can include the sig in a post with the line:

<exec type="function" name="ardamis_halo3" params="YOURTAG" />

Apricot is a text-heavy and graphic-light, widget- and tag-supporting minimalist WordPress theme built on a Kubrick foundation. Apricot validates as XHTML 1.0 Strict and uses valid CSS. It natively supports the excellent Other Posts From Cat and the_excerpt Reloaded plugins, should you want to install them.

WordPress version 2.3 introduces native support for ‘tags’, a method of organizing posts according to key words. Apricot has been updated to use this native tag system. The tag cloud will appear in the sidebar and the tags for each post appear above the meta data.

I used Apricot on this site for over a year, making little tweaks and adjustments the whole time, so the theme is pretty thoroughly tested in a variety of different browsers and resolutions. While the markup is derived from the WordPress default theme, Kubrick, I’ve added a few modifications of my own. I’ve listed some of these changes below.

header.php

  • Title tag reconfigured to display “Page Title | Site Name”

single.php

  • Post title is now wrapped in H1 tags
  • Metadata shows when the post was last modified (if ever)
  • Added links to social bookmarking/blog indexing sites: Del.icio.us, Digg, Furl, Google Bookmarks, and Technorati
    I’ve published a fix for the Sociable plugin, which I’m now using instead of hard-coded links
  • If the Other Posts From Cat plugin is active, the theme will use it
  • Comments by the post’s author can be styled independently

page.php

  • Displays the page’s last modified date (instead of date of publication)

index.php

  • Displays the full text of the latest post and an excerpt from each of the next nine most recent posts
  • Native support for the_excerpt Reloaded plugin, if active

sidebar.php

  • Displays tag cloud, if tags are enabled

search.php

  • If no results found, displays the site’s most recent five posts

404.php

  • Displays the site’s most recent five posts

footer.php

  • Archive and index page titles + blog name wrapped in H1 tags

Screen shot

Apricot - A WordPress theme by Ardamis.com

Search engine optimization

Apricot takes care of most of the on-page factors that Google values highly. It places the post’s title at the beginning of the title tag and in a H1 tag near the top of the page. It is free of extraneous markup and the navigation is easily spiderable. It generates what I think is a pretty logical site structure from the various post and category pages, though I have yet to study the effect of the new tagging system.

I’ve had a few top-ranked pages with this and other structurally similar layouts. Your mileage with the search engines may vary, but the layout uses fundamentally sound structural markup, which should give your site a good start.

Download

Download the theme from http://wordpress.org/extend/themes/apricot or from the link below.

Download the Apricot WordPress Theme

What if I want to use an image as a header?

Lots of people would rather use a graphic as a header, including me, but the WordPress guys insist on each theme uploaded to http://wordpress.org/extend/themes/ display the blog title and tag line.

If you want to replace the blog title and tag line with an image, download this zip file and follow these instructions (also included in readme.txt).

1. Make a PNG image, name it “header.png” and upload it to the /wp-content/themes/apricot/images/ folder. It should be 800px wide by 130px tall, or less.

2. Replace the original Apricot theme’s header.php file with the header.php file from this folder.

Download the Apricot Image Header

Update 2.9.11: Kevin Fell has taken up the challenge of maintaining this plugin. Please find the latest release that works with the post January 20, 2011 update at http://www.kevin-fell.co.uk/development/x-box-360-gamercard-wordpress-plugin/.
Update 1.24.11: I realize the January 20, 2011 update to the gamercard has broken the plugin. Basically, the plugin expects the HTML of the gamercard to be exactly so, and the HTML of the new card doesn’t match the plugin’s expectations. I don’t know if I’ll update the plugin to work with the new gamercard.

I’ve put together a WordPress plugin that will display a customizable XHTML and CSS Xbox 360 gamer card. There are plenty of sites out there that will make good looking gamer cards using image files, but this method will give you complete control over the appearance. It also acts like a gamer card, with a link to your Xbox Live profile and “compare to” links to your five most recently played games, something the image file cards can’t do.

XHTML and CSS Xbox Gamercard WordPress Plugin

XHTML and CSS Xbox Gamercard WordPress Plugin

For those of you who want a raw PHP script with the same functionality, I’ve included one farther down in the post.

How the plugin works

The plugin uses cURL, a command line tool for transferring files with URL syntax, to read the contents of your Xbox Live gamer card from http://gamercard.xbox.com/YOURTAG.card into a string, and then uses the PHP function preg_match to perform regular expression matching on that string. The various elements of your gamer card are extracted and then assigned to variables for later output.

The plugin attempts to create a unique text file for each gamertag (gamercard_cache_YOURTAG.txt) for use as a cache in your blog’s root folder automatically. This is done to reduce the number of times the target HTML page must be accessed and parsed and therefore reduce server load and page load time. Some server configurations may not permit the plugin to create this file and you’ll see resultant errors; in this case, you may have to upload a file with that name and perhaps set permissions on the file. You can edit the plugin to adjust how old the cache can grow before the script refreshes the information from gamercard.xbox.com.

Usage

The plugin accepts two arguments: the first is your gamertag; the second, which is optional, toggles whether the recently played games are displayed.

Insert the code:

<?php if (function_exists('gamercard')) gamercard('YOURTAG'); ?>

into a template file wherever you want the gamer card to appear, replacing YOURTAG with your actual Xbox Live gamertag, ex.:

<?php if (function_exists('gamercard')) gamercard('ardamis'); ?>

You can include multiple, different gamer cards on each page.

Customization

To show the recently played games icons, add the “full” argument, ex.:

<?php if (function_exists('gamercard')) gamercard('ardamis', full); ?>

Do whatever you want with the CSS to integrate the gamer card into your site.

Installation

The download includes:

  • xbox-gamercard.php (put this in your /plugins/ directory)
  • gamercard.css (copy and paste the contents into your theme’s style.css)
  • /gc_images/ (optional – put this folder of reputation images in your WordPress theme’s /images/ folder if you want to use them)

The plugin by default now uses the gold stars with transparent background from the ‘mini-card’ in the top navigation of http://www.xbox.com/. The rep image is a transparent .png, however. If you’re worried that people using IE6 will see an ugly rep because of IE6′s lack of support for transparent .png, you may want to edit the plugin to use a different rep image. It’s easy.

screen shot of mini-card from Xbox.com

a screen shot of the ‘mini-card’ from Xbox.com

The optional ‘gc_images’ folder contains 20 images, one for each reputation rank, to replace the default gamercard gauge. They are based on the gauge used in the smaller, menu bar gamercard on the old http://live.xbox.com/ site, but with transparent backgrounds instead of gray for greater flexibility. You don’t need to use these, of course. I’ve written 3 variables into the plugin if you want to use the official Xbox rep images. Just edit the plugin to replace $navgamerrep in the output with one of the other variables. (Seriously, it’s easy.)

Download (beta 1.3)

Get the files here:

Download the Xbox 360 Gamer Card WordPress Plugin

I’m getting an error message

If your server does not have cURL enabled, you’ll get an error message that reads something like Fatal error: Call to undefined function curl_init() in PATHwp-contentpluginsxbox-gamercard.php on line 54. The best solution is to ask your host to enable cURL. If that option is unavailable, I’ve provided an alternative that uses the function file_get_contents(), but a number of hosts have disabled the URL retrieving capabilities in file_get_contents() for security reasons. Download the FGC Gamer Card WordPress Plugin only if you’re getting an error message with the regular download.

Can I get this as a WordPress Widget?

Honestly, the plugin is much more flexible than a widget. Widgets are limited to your sidebar, while the plugin can be used in any template. Installing the plugin isn’t very complicated, either. So, in short, there are no plans to adapt this as a widget right now.

How can I use this on a non-WordPress site?

Download the Xbox 360 Gamer Card Stand-alone Script

Just PHP include the xbox-gamercard-standalone.php script wherever you want the card to be displayed, adjusting the path to the reputation images. Add the contents of gamercard.css to your main CSS file, and modify to suit your site.

Be aware that message boards and forums (eg: vBulletin forums) won’t allow you to use PHP as part of your post or signature. In short, don’t expect this method to work anywhere but on your own site.

You can either edit the script to use your gamertag, or call the script with the line:

<?php include 'PATH-TO-SCRIPT/xbox-gamercard-standalone.php?tag=YOURTAG'; ?>

To show the recent games, use:

<?php include 'PATH-TO-SCRIPT/xbox-gamercard-standalone.php?tag=YOURTAG&full=full'; ?>

Obviously, you’ll replace ‘YOURTAG’ with your gamertag. If you have any spaces in your gamertag, replace each space with %20.

Further customization (optional)

A number of neat image and Flash sigs contain way more information than just what’s provided at http://gamercard.xbox.com/YOURTAG.card, but as far as I can tell, it’s all gathered in the same way. If there’s something you’d like added to the script, find a page that contains the information and post a comment about it, or give programming a shot yourself…

View the source code of the target page and locate the data you wish to extract. What we want to do is identify everything but the desired data. Isolate the desired data within the source code of the target page by copying everything from the first character before the data back to and including something unique, such as a div’s id. Paste that into a preg_match line as the first half of the pattern that the script will look for. Follow that with the characters (.+?), a bit of code that represents the data we want to extract. Do not copy the actual desired data from the target page into the modified script. Last, select and copy a few characters immediately after the data, such as the closing div, and paste that after the (.+?). Everything in between the two copied strings—the stuff now represented by the (.+?) characters—will be assigned to a variable.

Credits

Thanks to Constantin Hofstetter for getting me started on this project and to Jeremy at 360gamerCards.com for eliminating the need for the Snoopy script, reducing the process to a single file and otherwise greatly simplifying the whole thing. And thanks to everyone who emailed or posted with error messages and other problems; it’s a better, more robust plugin because of your efforts.

My gamertag is ardamis, should you want to add me to your friends list and give me some positive feedback.

I’ve happened across an apparent bug in the way Internet Explorer renders the Mootools Accordion javascript when inside a table. Specifically, I’m trying to use the Accordion to show and hide a new table row. I’ve put the stretcher div inside a td cell, which opens and closes correctly in Firefox, but exhibits two distinct problems in IE 6 and 7. For one, the action should be smooth, but is bouncy and jerky. For another, after the div collapses, it springs open a few pixels and remains that way, impacting the consistency of the table layout.

If anyone has any suggestions on how to correct this buggy behavior, I’d be much obliged.

I’ve written a WordPress plugin that will convert the page title and post title to ‘title case’ capitalization. Title case is also often referred to as “headline style”, and incorrectly as “initial caps” or “init caps”. Title case means that the first letter of each word is capitalized, except for certain small words, such as articles, coordinating conjunctions, and short prepositions. The first and last words in the title are always capitalized.

This plugin may be useful if you’re trying to give the titles on your site a consistent appearance, but it’s no substitute for writing a good title. There are way too many exceptions and rules to make a simple script behave correctly all of the time.

The plugin is smart enough to not capitalize the following:

  • Coordinating conjunctions (and, but, or, nor, for)
  • Prepositions of four or fewer letters (with, to, for, at, and so on) (limited)
  • Articles (a, an, the) unless the article is the first word in the title

But the plugin isn’t perfect. It won’t capitalize an article that is the last word in the title. It fails on subordinating conjunctions. It conservatively de-capitalizes only some of the prepositions, hopefully reducing the chance of incorrect behavior. For example, it leaves the word over caps, because over can be an adverb, an adjective, a noun, or a verb (caps) or a preposition (not caps), and determining how a word is being used in a title is really beyond the scope of a humble plugin.

The plugin requires you to edit it for certain product names, like “iPod”, and cool-people names, like “Olivia d’Abo” or “Jimmy McNulty”. It’s not savvy enough to know that acronyms, like “HTML”, should be all caps unless they’re used in particular ways, such as in the case of “Using the .html Suffix”, unless you tell it. That said, editing the plugin for these particular words is very easy.

Even with all these limitations, it beats using CSS to {text-transform: capitalize} the titles or just applying PHP’s ucwords() to the entire thing. But I’m guessing that dissatisfaction with one or both of those two methods is what brought you to this page in the first place.

On the upside, it capitalizes any word following a semicolon or a colon, e.g.: “Apollo: A Retrospective Analysis”. It also capitalizes any word immediately preceded by a double or single quote, but only if you haven’t bypassed WordPress’s fancy quotes feature.

How it works

The plugin first finds all words that begin with a double or single fancy WordPress quote and adds a space behind the quote. It capitalizes all of the words in the title with ucwords(), then selectively de-capitalizes some of the words using preg_replace(). It then uses str_ireplace(), a case-insensitive string replace function, to correct the odd capitalization of certain other words. Finally, it removes the spaces behind the quotes.

The code

This is what the code looks like. It should be pretty easy to follow what’s happening.

<?php

function ardamis_titlecase($title) {
		$title = preg_replace("/&#8220;/", '&#8220; ', $title); // find double quotes and add a space behind each instance
 		$title = preg_replace("/&#8216;/", '&#8216; ', $title); // find single quotes and add a space behind each instance
		$title = preg_replace("/(?<=(?<!:|;)W)(A|An|And|At|But|By|Else|For|From|If|In|Into|Nor|Of|On|Or|The|To|With)(?=W)/e", 
'strtolower("$1")', ucwords($title));  // de-capitalize certain words unless they follow a colon or semicolon
		$specialwords = array("iPod", "iMovie", "iTunes", "iPhone", " HTML", ".html", " PHP", ".php"); // form a list of specially treated words
		$title = str_ireplace($specialwords, $specialwords, $title); // replace the specially treated words
		$title = preg_replace("/&#8220; /", '&#8220;', $title); // remove the space behind double quotes
		$title = preg_replace("/&#8216; /", '&#8216;', $title); // remove the space behind single quotes

		return $title;
}

add_filter('wp_title', 'ardamis_titlecase');
add_filter('the_title', 'ardamis_titlecase');

?>

Download

Download the plugin, upload it to your site, and activate it.

Download the Title Case Capitalization WordPress plugin

Further customization

The plugin won’t alter words written in all caps or CamelCase. You could use ucwords(strtolower($title)) to convert the entire $title to lowercase before applying ‘ucwords’. This may fix instances where someone has typed in a bunch of titles with the caps lock key on. But you’ll then have to compensate for words that should be all caps, like ‘HTML’, ‘NBC’, or ‘WoW’, in $specialwords.

An alternative using a ‘foreach’ loop

It’s possible to do something similar using a foreach loop. This isn’t as graceful, in my opinion, but I suppose it’s possible that someone may find it works better.

<?php

function ardamis_titlecase($title) {
	$donotcap = array('a','an','and','at','but','by','else','for','from','if','in','into','nor','of','on','or','the','to','with'); 
	// Split the string into separate words 
	$words = explode(' ', $title); 
	foreach ($words as $key => $word) { 
		// Capitalize all but the $donotcap words and the first word in the title
		if ($key == 0 || !in_array($word, $donotcap)) $words[$key] = ucwords($word); 
		if (preg_match("/^&#8220;/", $word))
			$words[$key] = '&#8220;' . ucwords(substr($word, 7));
		elseif (preg_match("/^&#8216;/", $word))
			$words[$key] = '&#8216;' . ucwords(substr($word, 7));
	} 
	// Join the words back into a string 
	$newtitle = implode(' ', $words); 
	return $newtitle; 
}

add_filter('wp_title', 'ardamis_titlecase');
add_filter('the_title', 'ardamis_titlecase');

?>

Credits

Thanks to Chris for insight into the preg_replace code at http://us2.php.net/ucwords. Thanks to Thomas Rutter for insight into the foreach code at SitePoint Blogs » Title Case in PHP.

I needed to find a satisfactory way of adding WordPress tags and theme elements (such as the sidebar) to pages that exist outside of WordPress. A non-WordPress page could then appear to be seemlessly incorporated into the site, wherein the layout automatically updates with changes to the theme template files, and could use the same header, sidebar, and footer as a normal WordPress page.

The first few solutions that I found involved adding a line to each non-WordPress page. This does indeed allow the page to incorporate WordPress tags, theme elements and styles, but there is a serious drawback to this method because of the way WP manages a web site.

When you click on the link to a WP page, or enter it into the address bar, you aren’t actually going to a file that resides at that address. Instead, WP uses that address as an instruction to pull various database entries and form an index.php page that resides in the WP installation directory. For example, while the address for this page appears to be http://www.ardamis.com/2006/07/10/wordpress-googlebot-404-error/ , the actual page is at http://www.ardamis.com/index.php.

WordPress assumes that it is responsible for every page on the site, and that there are no pages on the site that it doesn’t know about. If you try to browse to a page that WP doesn’t know about, it sends you a 404 error page instead. This is what you want it to do, so long as you don’t create any pages outside of WordPress.

But a problem arises when you do want to create a page that WP doesn’t know about. When you visit the page, WP checks the database and finds that it doesn’t exist, so it puts a 404 error in the http header, but the page does exist, so Apache sends the page with the 404 error. This behavior seemed to cause some problems with some versions of IE but none with Firefox. It did, however, result in a 404 header being given to Googlebot, so that non-WordPress pages would incorrectly show up in Google Sitemaps as Not Found.

To get around this problem and send the correct http header code: HTTP Status Code: HTTP/1.1 200 OK, I needed to require a different file, wp-config.php, and then select specific functions for use in the page. results in a page that can use all of the desired tags and theme elements and also sends the correct header code: HTTP Status Code: HTTP/1.1 200 OK

The following code results in a page that can use all of the tags and theme elements (you may need to adjust the path to wp-config.php):

<?php require('./wp-config.php');
$wp->init();
$wp->parse_request();
$wp->query_posts();
$wp->register_globals();
?>

<?php get_header(); ?>

<div id="content">
<div class="post">
<h2>*** Heading Goes Here ***</h2>
<div class="entry">
*** Content in Paragraph Tags Goes Here ***
</div>
</div>
</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>

Testing the method

Using wp-blog-header.php as the include, I created a GoogleBot/WordPress 404 Testing Page as the index.php file in the /testing/ folder. I added the url http://www.ardamis.com/testing/ to my Google xml sitemap, and waited for the sitemap to be downloaded. Sure enough, a few days later Google Sitemaps was listing the /testing/ url among the Not Found errors.

The next step was to remove what I suspected was the culprit, the include of the WordPress header, wp-blog-header.php, and see if Googlebot could again access the page. A few days after removing the include, and after the sitemap was downloaded, the Not Found error disappeared. I’m interpreting this as Googlebot once again successfully crawling the page.

The third step was to use the above code, including wp-config.php and then testing the HTTP Request and Response Header. The header looks ok, and Googlebot likes it. It looks like this does the trick.

This post was written in 2006. As of WordPress 2.5 (released in 2008), a new seplocation parameter has been added to wp_title. This allows you to reverse the page title and blog name in the title tag, in much the same way as I have described in this post. The page at http://codex.wordpress.org/Function_Reference/wp_title provides this example:

<title><?php wp_title('|',true,'right'); ?><?php bloginfo('name'); ?></title>

I’d recommend using it, instead of the admittedly complicated instructions below.

Getting the title tag just right in WordPress isn’t as easy as it ought to be. Currently, a popular title syntax for SEO purposes shows the page’s title, followed by a pipe separator, followed by the site’s name. In practice, this preferred syntax would appear as “Page Title | Site Name”. For whatever reason, the default theme in WordPress has this order reversed, so that each page’s title starts with the blog name, followed by a » separator, some useless clutter, another » separator and then the page’s title. The instructions below will help you optimize the title tag to take advantage of the prefered method.

The code for the default WordPress title tag, which is found in the “header.php” file, looks like this:

<title><?php bloginfo('name'); ?> <?php if ( is_single() ) { ?> &raquo; Blog Archive <?php } ?> <?php wp_title(); ?></title>

It seems like it should be an easy thing to clean up. We remove the unnecessary “Blog Archive” stuff and then switch the two title template tags, putting <?php bloginfo('name'); ?> behind <?php wp_title(); ?>.

Our title tag code now looks like this:

<title><?php wp_title(); ?><?php bloginfo('name'); ?></title>

But if you make this obvious change and reload one of your blog’s post pages in your browser, you’ll notice that the separator, which is inextricably part of the wp_title template tag, wants to be in front of the page title and is now the very first character in your browser’s title bar, resulting in something like “» Page Title Blog Title”. Furthermore, we are missing a desired separator between the page title and the blog title.

Let’s first do something about that initial separator. The wp_title tag we’ve been using so far, <?php wp_title(); ?>, is abbreviated, meaning that there are some options that are being allowed to fall back to their default states because we haven’t specifically provided otherwise. Changing the behavior of the wp_title separator is as easy as manipulating these options in the unabbreviated wp_title template tag. The full tag, including the options, looks something like: <?php wp_title('sep', display); ?>, where ‘sep‘ stands for whatever separator you want and display is either “true” or “false”, depending on whether you want the title displayed. For example, if you want to use the pipe symbol ” | ” to appear at the beginning of your post title, you would use: <?php wp_title('|'); ?>. (The display option defaults to “true”, which is what we want here, so I’ll omit that part in the future for the sake of brevity.)

This fiddling with different separators works just fine when the elements of the title are in the default order, but when we put wp_title at the beginning of our title tag, we get a separator as the first character in our title. We don’t want a separator in front of the Page Title, so we will use the ‘sep‘ option described above to tell WordPress to use an empty string (represented by the absence of text between two quotes) as the separator, like so: <?php wp_title(''); ?>. This is the preferred method for removing the leading separator from the wp_title tag. Now the code for our title tag looks like:

<title><?php wp_title(''); ?><?php bloginfo('name'); ?></title>

This title will cause your browser’s title bar to display “Page Title Blog Name”. We are getting closer to what we want.

Without explaining exactly how it works, let me just offer you an optional line of code to selectively add or omit a separator between the Page Title and the Blog Name as appropriate for each page: <?php if(wp_title(' ', false)) { echo ' | '; } ?>. Place this line of code between the wp_title and bloginfo template tags, as so:

<title><?php wp_title(''); ?><?php if(wp_title(' ', false)) { echo ' | '; } ?><?php bloginfo('name'); ?></title>

Reload the page again, and your title bar should show you exactly what we want, “Page Title | Blog Name”, without a leading separator. Any page without a Page Title, the home page, for example, will just have “Blog Name” in the title tag. Everything up to this point is explained on the WordPress Codex page dealing with Template Tags/wp_title. For most users, this is as far as one wants or needs to go to achieve the desired result.

Further optimization

But… if you’re really humorless about clean code, there’s more to be done. If you view the source code of these pages, you’ll notice that there are a handful of spaces after the opening title tag and before your Page Title. Yikes. Lucky for you, I like my code to be tidy and am also pretty interested in SEO, and for both of these reasons, albeit in unequal parts, these leading spaces in the title tag are unacceptable.

There are three ways to make WordPress close up the spaces whenever we declare an empty string as our separator, as in: <?php wp_title(''); ?>. The first method requires editing a file in the WordPress core. The second method is accomplished by adding a few lines of code to your theme’s ‘functions.php’ file. The third method uses a simple plugin.

Using any of these methods to remove the spaces will also remove the separator that WP wants to add between the year, month, and DD.MM.YY date of the titles of the monthly archives. So if your separator was a pipe symbol, they looked something like: 2006 | December | 17.12.06 | Ardamis.com and after removing the spaces they will look like: 2006 December 17.12.06 | Ardamis.com

Method 1 – the core file

This method involves hacking a core file. This is the most direct way to get the desired result. It basically corrects the problem the moment it happens.

For WordPress version 2.2

The file we want to edit is: wp-includesgeneral-template.php. Open it up and find the following lines (beginning at line 224):

$prefix = '';
if ( !empty($title) )
	$prefix = " $sep ";

Add the line if ( $prefix == ' ' ) { $prefix = ''; } below the block, so that the block now reads:

$prefix = '';
if ( !empty($title) )
	$prefix = " $sep ";
	
if ( $prefix == '  ' ) { $prefix = ''; }

Method 2 – functions.php

If you’re not comfortable editing a core file, and if you don’t want to install yet another plugin, this method will also work. Open the ‘functions.php’ file in your theme folder and add the following lines. Depending on your theme, functions.php may already contain some PHP code; that’s ok, just tuck this in at the end. The first line of functions.php should be <?php and the last line should be ?>. If those lines don’t exist, add them and then add the following code between them.

function af_titledespacer($title) {
	return trim($title);
}

add_filter('wp_title', 'af_titledespacer');

Method 3 – a plugin

If plugins are more your speed, you can get the same results with my Despacer plugin.

Download the Despacer WordPress plugin

Utilizing the changes in the template files

We can now remove the separator and the annoying blank spaces on an instance-by-instance basis by specifying an empty string as the separator, as so: <?php wp_title(''); ?>. By way of example, to hide the separator and remove the blank spaces, a “Page Title | Blog Name” title tag would look like:

<title><?php wp_title(''); ?><?php if(wp_title(' ', false)) { echo ' | '; } ?><?php bloginfo('name'); ?></title>

If anyone finds a better way of arriving at this result, preferably entirely within the template files, please leave me a comment, or post to the WordPress support forum.

You may notice that one poster to the WordPress forums suggests that the search engines don’t care if there is white space in a web page. While I agree that the search engines and browsers don’t have any problem parsing pages that contain chunks of white space, a gap at the beginning of the title tag looks very unnatural to me. No human would intentionally add a bunch of blank spaces to the beginning of the tag, and it’s generally understood that for SEO purposes, a page that looks handcrafted is superior to one that looks like it has been slapped together by a script. This may not be a problem now, but Google and the other search engines are constantly working to remove spam/garbage/scraped sites from their results, and they may one day use weirdly unnatural artifacts like this to identify them.