Posts Tagged ‘blogging’

Adding ‘Related Posts’ to WordPress articles and 404 error pages

Tuesday, July 22nd, 2008

Many blogs have a list of related articles after each of their posts. I wanted something similar for my WordPress blog but found it wasn’t as easy to do as I thought it would be.

At the same time I was interested in capturing any access attempts to non-existent pages (causing a 404 error), and showing a list of suggested links. This is something that is useful to do to turn people who get 404 errors into readers of your blog.

I first looked at the WASABI related post plugin. It did what I wanted with the related entries but it requires you to add a tag to each post where you want the related entries to appear. There is also a version of the plugin which can generate sensible links for any 404 errors. It does this by turning the incorrect URL into a list of terms which are then used to find related posts.

The next plugin that I read about was called ‘Aizattos Related Posts’. This plugin was originally based on WASABI but has evolved since. It inserts related links without needed to add any special tags to the posts. A lot of good feedback was given about this plugin but it seems that the author has removed it from the original download site. Fortunately someone has re-posted this plugin to this site.

I therefore have what I need in two separate plugins. I installed the Aizattos Related Posts plugins and then created a modified version of the WASABI 404 handling code. The 404 handler is in one function ‘related_posts_404’. Below is the modified version of the WASABI code which will work with the Aizattos Related Posts plugin. As well as showing the related links it also shows an extract from the post page. Just put this function in the Aizattos Related Posts plugin PHP file.

related_posts_404()
function related_posts_404($limit=5, $len=50,
	$before_title = '', $after_title = '',
	$before_post = '', $after_post = '',
	$show_pass_post = false, $show_excerpt = true) {
    global $wpdb, $post;
    $before_title   = '<span class="aizatto_related_posts_title" >';
    $after_title    = '</span>';
    $before_excerpt = '<div class="aizatto_related_posts_excerpt">';
    $after_excerpt  = '</div><p></p>';
    $before_related = '<li>';
    $after_related  = '</li>';
    $search_term = $_SERVER['REQUEST_URI'];
    $search = array ('@[/]+@', '@(..*)@', '@[-]+@', '@[_]+@', '@[s]+@', '@archives@','@(?.*)@','/d/');
    $replace = array (' ', '', ' ', ' ', ' ', '', '','');
    $search_term = preg_replace($search, $replace, $search_term);
    $search_term = trim($search_term);
    $terms = $search_term;
    $time_difference = get_settings('gmt_offset');
    $now = gmdate("Y-m-d H:i:s",(time()+($time_difference*3600)));
    // Primary SQL query
    $sql = "SELECT ID, post_title, post_content,"
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') AS score "
         . "FROM $wpdb->posts WHERE "
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') "
		 . "AND post_date <= '$now' "
         . "AND (post_status IN ( 'publish',  'static' ) && ID != '$post->ID') ";
    if ($show_pass_post=='false') { $sql .= "AND post_password ='' "; }
    $sql .= "ORDER BY score DESC LIMIT $limit";
    $results = $wpdb->get_results($sql);
    $output = '';
    if ($results) {
        foreach ($results as $result) {
            $title = stripslashes(apply_filters('the_title', $result->post_title));
            $permalink = get_permalink($result->ID);
            $output .= $before_title
                .'<a href="'. $permalink .'" rel="bookmark" title="Permanent Link: '
		. $title . '">'
		. $title . '</a>'
		. $after_title;
            if ($show_excerpt=='true') {
                $post_content = strip_tags($result->post_content);
                $post_content = stripslashes($post_content);
                $words=split(" ",$post_content);
                $post_strip = join(" ", array_slice($words,0,$len));
                $output .= $before_excerpt . $post_strip . $after_excerpt;
                }
        }
        echo $output;
    } else {
        echo $before_title.'Fuzzy ...'.$after_title;
    }
}

Although no code modifications are needed for the related links in your normal posts, you will have to make a modification to your theme’s 404 page if you want related links for any ‘Not Found’ errors. In blue below is the modification I made to my 404.php for the default theme.

blog/wp-content/themes/default/404.php
<?php get_header(); ?>
	<div id="content" class="narrowcolumn">
		<h2 class="center">Error 404 - Not Found</h2>
		<p>We're sorry but the page you are looking
		for isn't at this location. Were you perhaps
		looking for one of these articles?</p>
		<?php related_posts_404(); ?>
	</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>


Claiming your WordPress blog in Bloglines

Friday, May 16th, 2008

After having claimed my blog in Technorati (see previous post) I thought I’d try to do the same in Bloglines. They have a completely different way of verifying ownership.

They require you to add a hidden tag to your blog template and in one of your blog posts. They tell you what to add but they don’t explain how to do it. A search on Google reveals that a lot of people with self-hosted WordPress blogs seem to be finding it very hard to claim their blogs.

Due to the lack of instructions I made a guess at what to do and managed to get my blog claimed first time. Maybe I’m just lucky! :) This is what I did. Note that these instruction are for self-hosted WordPress blogs and may not apply for other blog platforms or for blogs hosted on the WordPress site.

In the Publisher Tools section of my account on Bloglines I went through the basic steps of adding my blog URL until I got to the page giving the claim tags. As you can see the page gives no clues as to how you are supposed to apply the tags to your blog.

bloglines blog claim

I use the Default theme on my site so I edited the header.php which lives here:
wp-content/themes/default/header.php

If you use a different theme you should modify the equivalent page in your theme.

I added the tag in the <head></head> section of the site as this tag isn’t designed to be viewed. You could probably add it anywhere in the <head></head> but here is where I added my tag.

<link rel="alternate" type="application/rss+xml"
 title="<?php bloginfo('name'); ?> RSS Feed"
 href="<?php bloginfo('rss2_url'); ?>" />
<link rel="pingback"
 href="<?php bloginfo('pingback_url'); ?>" />
<!-- ukey="3064F3CF" -->
<style type="text/css" media="screen">

Then I went into the Manage section of my WordPress control panel and edited the latest post using the non-WYSIWYG plain text editor. I inserted the blog tag at the very top of this post. This tag is non-viewable so you don’t need to worry about anyone seeing it.

bloglines add tag to new post

After doing this I went back to Bloglines and pressed the button to verify my claim. And it worked!

bloglines verification ok

Quick Claiming your blog on Technorati without giving up your password

Friday, May 16th, 2008

Today I had a go at claiming my blogs on Technorati. Claiming your blog gives you a bit more control over how your blog appears on the Technorati site. You can edit the blog description, add a user image and add tags.

In order to claim your blog you must prove that you own it. There are two ways to do this; Quick Claim or Post Claim. Post Claim involves writing a new post with a visible tag in it. I didn’t really fancy doing this. The other method is Quick Claim. To Quick Claim you need to enter your blog username and password. Technorati will then log into your blog to check that you are the owner. This option sounded like less hassle but I didn’t want to give them my real password. They say that they don’t store it but I think it is best not to take any chances.

technorati blog claim

What I decided to do was to create a new temporary user for the purposes of claiming my blog. After it was claimed I could delete it. Here’s how to do it using a self hosted WordPress blog. Something similar will probably work for other blog software.

In your WordPress control panel go to Users->Authors & Users. Then add a new user. Use a different password to your usual one. You’ll need to give your new user the Administrator role. I tried with the other roles but Technorati won’t accept anything less than an Admin account.

wordpress add new user

I then went back to the Technorati website entered my temporary admin user details and it worked!

technorati blog claim

Once your blog is claimed remember to delete your temporary user – but take care – don’t accidently delete yourself my mistake!

Adding spacing round an iframe in WordPress

Wednesday, March 5th, 2008

It was whilst writing a review of the book ‘boo hoo’ that I spotted a problem with embedding iframes in WordPress postings. As I was reviewing a book I wanted to add an Amazon Product link. These product links are in the form of iframes. An example of the HTML is below. I added the align="right" myself as I wanted the text to flow around the iframe.

<iframe src="http://rcm-uk.amazon.co.uk/e/cm?t=advancedhtml-
21&o=2&p=8&l=as1&asins=0099418371&fc1=000000&IS2=1
&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr"
style="width:120px;height:240px;" scrolling="no"
marginwidth="0" marginheight="0"
frameborder="0" align="right"></iframe>

You can see from the image that in WordPress (in the default theme anyway) there is no spacing between the left edge of the image and the text. This looks wrong so I wanted to find a solution to this.

Amazon iframe problem

It seems that there are no padding tags that you can add to an iframe unless you use style sheets. I wanted a simple solution that I could just embed in the HTML. The solution that I chose was to put the iframe in a table and set the cellspacing attribute of the table to the required amount padding. Instead of using align in the iframe I am now using it in the table. The HTML and result of this change are shown below.

<table border="0" cellspacing="10" align="right"><tr><td>
<iframe src="http://rcm-uk.amazon.co.uk/e/cm?t=rmlcouk-
21&o=2&p=8&l=as1&asins=0099418371&fc1=000000&IS2=1
&lt1=_blank&lc1=0000FF&bc1=000000&bg1=FFFFFF&f=ifr"
style="width:120px;height:240px;" scrolling="no"
marginwidth="0" marginheight="0"
frameborder="0"></iframe>
</td></tr></table>

Amazon iframe fix

You’ll probably agree that the Amazon product links looks much better with the extra spacing.

Improved KML embedding of Google Maps into web pages

Sunday, December 23rd, 2007

I’ve been further improving the code that I described in my previous in my previous post – ‘Adding KML Google Maps overlays to WordPress posts‘.

I’ve made these changes:

  1. Option to specify a latitude / longitude / zoom for the map. This allows you to have one map and then show lots of different views of it
  2. The code is now implemented as a function rather than as included PHP. This means that the full map can be included in one line of PHP and the code only has to be included once in each page.

As before you can include a whole map which will be automatically centred and zoomed for you. The require_once is only needed once on each page, but no harm will come to you if it is included more than once. Only one argument is needed – the full URL to the KML file. A width / height can be included if you want.

<?php
require_once('../data/071223/mapiframe.php');
iframe("https://www.reviewmylife.co.uk/data/071223/track.kml");
?>

In the require_once you can either include an absolute path or a relative path.


View Larger Map
The new options allow you to specify the latitude, longitude and zoom values. When you specify these values you also have to specify the width / height of the map. The argument list is:

  1. Full URL of KML – note this is the full URL not a relative one
  2. Width of map – in pixels
  3. Height of map – in pixels
  4. Latitude
  5. Longitude
  6. Zoom
<?php
require_once('../data/071223/mapiframe.php');
iframe("https://www.reviewmylife.co.uk/data/071223/track.kml",
	450, 400, "51.515339", "-0.054374", 15);
?>


View Larger Map
To get the latitude / longitude / zoom values view your KML file in Google Maps. Click on ‘Link to this page’ as described in the previous post. Alter the zoom and position of the map so it shows that you want. Then copy the latitude / longitude / zoom values from the HTML box. The latitude / longitude are the values in the ‘ll’ parameter (latitude is first). The zoom is the ‘z’ parameter.

So if we are looking at the following page in Google Maps.

Getting latitude, longitude, and zoom values from Google Maps

The latitude is 51.49966, the longitude is -0.053108 and the zoom is 16.

Here are the three files you’ll need.

MapIframe.php
LoadMap.php
GoogleMapLoader.js

You can see a demonstration of these scripts at www.londonphotoproject.co.uk/blog/. Here I have one KML file for my whole walking route, but I include multiple zoomed-in views of the map so I can describe the route in small sections.

For these scripts to work they’ll need to be interpreted as PHP4 rather than PHP5. If your web host is interpreting PHP files as PHP5 by default (which more and more of them are) simply put these PHP files in a separate directory and add a .htaccess with the following contents to that same directory.

# Treat files in this directory as PHP4
AddType x-mapp-php4 .php


Adding KML Google Maps overlays to WordPress posts

Thursday, December 20th, 2007

Embedding basic KML Maps into your blog post

There is an easy way to include Google Maps KML overlays in your WordPress blog if you are willing to have all the size and style information hardcoded into each post. All you have to do is to go to http://maps.google.co.uk/ type the KML location into the search box and then click on ‘Link to this page’.

Embedding KML into your WordPress blog using Google Maps

You can then add the HTML into your blog post by copy / pasting it from the second text box.

HTML for embedding Google Maps in a WordPress blog post

Google make it easy to change simple settings such as the map size by following the ‘Customise…’ link. Below is what the actual embedded map would look like. Handily the map is automatically zoomed into whatever data is in your KML file – In this example we’re looking at a walking track across London.


View Larger Map

This is great for if you want to add the odd maps to your blog, or if you don’t believe you’ll need to alter the style later on. The problem comes if you want to separate all the style information out of the embedded map iframe.

The problem with the Google Maps HTML generator

Imagine if you had a site with dozens or even hundreds of embedded KML files. One day in the future you decide that you want to change the style and look of all the maps. Maybe you want to change the size, add some extra links under each map, or add new features from the Google Maps API to each map. Below is what the actual HTML code embedding this KML file looks like. As you can see it is pretty ugly and it wouldn’t be fun to edit dozens / hundreds of these to change the way they look.

<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;geocode=&amp;time=&amp;date=&amp;ttype=&amp;q=http:%2F%2Fwww.reviewmylife.co.uk%2Fdata%2F071220%2Ftrack_east_london.kml&amp;ie=UTF8&amp;ll=51.497414,-0.054315&amp;spn=0.044967,0.044325&amp;om=0&amp;output=embed&amp;s=AARTsJozG9M05ndgSB8zlZU1Qavi7qH_cw"></iframe><br /><small><a href="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;geocode=&amp;time=&amp;date=&amp;ttype=&amp;q=http:%2F%2Fwww.reviewmylife.co.uk%2Fdata%2F071220%2Ftrack_east_london.kml&amp;ie=UTF8&amp;ll=51.497414,-0.054315&amp;spn=0.044967,0.044325&amp;om=0&amp;source=embed" style="color:#0000FF;text-align:left">View Larger Map</a></small>

Under normal circumstances it would be easy to separate out this code into a different file and pass in the KML file URL as a parameter. The problem is that Google have added a security parameter to the argument list (s=AARTsJozG9M05ndgSB8zlZU1Qavi7qH_cw in this case) which locks in the KML URL. You can edit the style parameters (width / height etc) but you can’t change the URL. If you do you get an error saying “Forbidden Your client does not have permission to get URL…”. Google have done this so they can keep a track of how much load individual sites are putting on their server. Unfortunately it means that if you want to use a new KML you have to use the Google Maps site to generate the HTML.

A solution and another problem for WordPress bloggers

There is a way around this, and that is to use the Google Maps API. This will allow you to programatically include as many KMLs as you want without using Google’s HTML generator. To use the API you have to sign up for a Google Maps API Key. There is one final problem – each key can only be used from one individual web directory. This can be a big problem if you are a WordPress user. Bill from the techrageo blog has already written about this so I won’t repeat what he has said. You can read his blog and look at his solution for yourself.

There are however some problems with his solution.

  1. You would need to create a new HTML file for each Google Map you are embedding.
  2. The width and height of the iframe have to be embedded in each map in each blog post or HTML page that you use it on.
  3. The JavaScript in his solution doesn’t quite do what I want.

Here is my solution which is inspired by his but solves these three issues. Please note that as with Bill’s solution this will require some programming knowledge. You will need to make modifications to my scripts to get them to work on your site.

To embed a KML file with my solution all you have to do is include a small section of PHP in your blog post. To allow me to embed PHP in my blog posts I’ve installed the Exec-PHP plugin. This is what the PHP looks like.

<?php
$mapxml="https://www.reviewmylife.co.uk/mymap.kml";
require('../data/kml/mapiframe.php');
?>

You must set the $mapxml variable which points to your KML file – it has to be the full URL, not a relative one. You then load the mapiframe.php file with the ‘require’ command. Optionally you can set a $width and a $height variable for the width/height in pixels, but this will re-introduce problem number 2. If you don’t set these values then default sizes (which you can change) will be used.

Embedding the KML with this PHP means that your blog posts now don’t contain any formatting infomation for the maps. All the formatting can be controlled from the following common scripts.

This is what your mapiframe.php looks like, it contains the common iframe information. You will probably need to fix the link to the loadmap.php file for your own web server.

<?php
/*
Include a KML on WordPress Blog
See www.reviewmylife.co.uk for details.
*/
if (!isset($mapxml))
	{
	print "ERROR: Missing mapxml";
	exit;
	}
if (!isset($width))
	{
	$width = "450";
	}
if (!isset($height))
	{
	$height = "450";
	}
$mapxml = urlencode($mapxml);
$widthparam="width=$width";
$heightparam="height=$height";
print <<<ENDHTML
<iframe width="$width" height="$height" scrolling="no"
frameborder="0" marginheight="0" marginwidth="0"
src="/data/kml/loadmap.php?mapxml=$mapxml&amp;$widthparam&amp;$heightparam">
If you see this, your browser doesn't support iframes.
Please upgrade to a more recent browser.</iframe><br /><small>
<a href="http://maps.google.co.uk/maps?f=q&amp;hl=en&amp;q=$mapxml&amp;ie=UTF8&amp;om=1&amp;source=embed"
style="color:#0000FF;text-align:left">View Larger Map</a></small>
ENDHTML
?>

Here is the code for loadmap.php. You’ll need to replace the Google Maps API key with your own one.

<?php
/*
Include a KML on WordPress Blog
See www.reviewmylife.co.uk for details.
Remember to replace the Google API key with your
own one or this script won't work!
*/
if (!isset($mapxml))
	{
	print "ERROR: Missing mapxml";
	exit;
	}
if (!isset($width))
	{
	$width = "450";
	}
if (!isset($height))
	{
	$height = "450";
	}
print <<<ENDHTML
<html>
<head>
  <title>Google Map Loader - $mapxml</title>
  <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA6Y9TsXMv7cdqyP8VLw2boRSTFKCAindh81v9qdSRu-QtalZoMBQj6TDiTZizmDy7aoJTqU6iO3pDOQ" type="text/javascript"></script>
  <script src="googlemaploader.js"></script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map" style="width:$width; height:$height"></div>
<span id="mapxml" name="$mapxml"></span>
<script type="text/javascript">
 function initialize() {
  if (GBrowserIsCompatible()){
   LoadGoogleMap();
   }
  }
</script>
</body>
</html>
ENDHTML
?>

This is the googlemaploader.js file which loads the KML using the Google Maps API. It correctly sets the viewport in the map view and adds a few controls to the map.

// Script to load and position a KML/XML Google Map
// See www.reviewmylife.co.uk for details.
var kml;
function LoadGoogleMap(){
  // Find mapinfo span and get name attribute
  var mapxml = document.getElementById('mapxml').getAttribute('name');
  kml = new GGeoXml(mapxml, PositionMapCallback);
}
function PositionMapCallback(){
  var map = new GMap2(document.getElementById("map"));
  map.addControl(new GSmallMapControl());
  map.addControl(new GMapTypeControl());
  kml.gotoDefaultViewport(map);
  map.addOverlay(kml);
}

This is the final result. Yes it looks very similar to the one generated by the Google Maps HTML generator. But if I ever need to change all my embedded maps it will be really easy for me.


View Larger Map
Here are some download links for the three files you need.

MapIframe.php
LoadMap.php
GoogleMapLoader.js

You’ll need to change the Google API key in loadmap.php. You’ll also need to fix the inter-file references so all the scripts reference each other correctly. All three scripts should be placed in the directory that you created the Google API key for.

Update: Make sure you check out my Improved KML embedding of Google Maps into web pages post for some updates to these scripts.

Adding source code into WordPress blog posting

Sunday, October 21st, 2007

As demonstrated by another post of mine I finally figured out how to easily add source code into a WordPress blog posting. Searching on Google for this issue reveals large numbers of people facing the same problem. It makes you think that including source code in a WordPress 2.2.1 blog posting is the most difficult problem known to man.

Many of the problems seem to be caused by the visual editor in WordPress. It reformats code in ways that you are unlikely to want (such as trimming any whitespace), leaving your carefully constructed source code looking like a real mess.

The way to turn it off is to go to ‘Login -> Users -> Edit’ and then untick the ‘Use the visual editor when writing’. There seems to be no way to edit and then re-edit in-line source code when the visual editor is turned on, because when you re-edit your posting the visual editor reformats your code automatically – even if you don’t make any changes and switch straight to the code editor.

This problem is in part because if you have the visual editor enabled it becomes the default editor and re-formats any code that it loads. WordPress could easily fix this be allowing you to make the code editor the default editor so the visual editor only gets its hands on your posting if you give it permission. There is a discussion on the worpress.org site about this here.

If you still want to use the visual editor then the workaround that I’ve seen mentioned is to create a second user account with the visual editor turned on. You then need to use the correct account depending on whether you will post source code or not and remember never to load your source code posts with the visual editor.

The next problem that I came across was that adding code within <pre></pre> tags causes the lines to be double spaced when using the default WordPress theme. I solved this by installing the CodeMarkup plugin which allows code samples to be displayed in a way which looks sensible to me. It automatically escapes all your code so that you can paste it directly in between <pre><code></code></pre> tags without having to use a tool tool to escape the special characters.

AddThis widget

Sunday, September 9th, 2007

I’ve been looking for a simple way to add those ‘Add to…’ buttons at the bottom of each of my blog entries. I’ve looked at a number of different methods of adding the buttons but the best one I’ve seen is the one from http://www.addthis.com/. It can be easily integrated into the major blogging tools.

If you use blogger you can easily update your blog template to include it. If you use WordPress then there is a simple plugin that you can use. There are a number of different versions of the AddThis widget but I’ve gone for the WordPress plugin of the drop-down version. Installing is easy. Just put the plugin in your WordPress plugins directory and activate it. By including your AddThis username in the php file you can get stats to tell you how often people have clicked on the links.

Update 2010: Due to layout and functional problems with AddThis I’ve switched the site over to Bookmarkify.

Setting up a WordPress blog on 1and1

Sunday, August 5th, 2007

Having decided to start a blog I had two main options for how to do it. Either create a blog using one of the many blog hosting sites, or host it myself on my own 1 and 1 web space. Hosting it myself is clearly the most flexible option, and for a techy like me the most fun. I did a bit of research into different blogging software and WordPress to me looks good enough for me.

I was initially a bit worried about the amount of MySQL database space that is needed for blog software. 1&1 databases are limited to 100mb and I wasn’t sure how much space WordPress would need. At work I manage a 5db database with the largest table having over 100 million rows so I’m well aware that databases can get big! Fortunately it seems that WordPress uses space very efficiently and even very large blogs only need a few megabytes.

WordPress comes with a load of documentation, but I did most of my setup by following the instructions on http://antbag.com/how-to-install-wordpress-with-1-and-1-hosting/ which has some good instructions specifically tailored for people on 1&1.

I’ve left the configuration pretty much at the default settings for now but I did add http://blogsearch.google.com/ping/RPC2 to the ‘Options->Writing->Update Services’ box so that Google Blog Search is notified for each update.