Writing a lightweight related content function for WordPress using tags to match content

Strangely, WordPress doesn’t ship with it’s own related content feature so there are a number available to download and use from the plugin directory. However, in my experience, most of these are quite resource-hungry, largely due to the fact that they build up the list of related content by string matching. This is a very expensive process and depending on the number of posts the script has to match against can lead to a slowdown in the database.

I’ve opted to write my own related content plugin using WordPress tags. Generally, a post should not have more than 5 tags attached to it. This makes the matching process much faster and less intensive on the database as tags are only ever matched against other tags attached to posts and never against the content of the posts themselves which could be lengthy.

Now this has the potential to get out of hand as tags can be easily entered by post authors leading to duplicates and unnecessary tagging which can then lead to poor relative matching. However, any professional organisation will have a publishing process and part of that should be for authors to avoid adding tags before checking if a suitable one already exists in the system.

View in Instagram ⇒

Redirect, don’t 404, when a web page is not found

The ‘Page Not Found’, or 404, error page is the default response for any request made to your website that can not be completed due to a missing file or resource.

Plain 404 error pageAll web servers issue the 404 error and the website, most often a content management system framework nowadays, like WordPress, acts on the 404 server response by displaying a page informing the user that the page requested via the url cannot be found.

Back in the day, the 404 error page was a plain, white page with some technical information. Worse than the lack of design, the page didn’t provide the user with any options or direction as to what to do next.

This was somewhat remedied when digital designers began creating 404 pages that had attractive design elements as well as information like links to the latest content and a search box to help the user find what they were looking for using keywords.

404 error page with space invaders gameMany of these 404 pages are works of art in their own right – some going so far as to incorporate interactive games. Many even encouraged the user to share the 404 page on social media!

The user-experience- and business-minded among you will immediately see why these attractive, interactive, share-worthy 404 error pages actually exacerbate the problem that a user is having; They’ve asked to see a certain page on your site and are instead presented with options to take them further away from the desired resource or to waste their valuable time with games. Any frustration your visitor is feeling by hitting a 404 page is likely to be amplified by these options.

A better solution is to automatically redirect the user to content that they are trying to access, but may not know the correct web address to get there. To illustrate I’ll use a simple example:

A user wants to see your About Us page and types http://mysite.org/aboutus.html into their browser. However, this page doesn’t exist; the real address of your About Us page is http://mysite.org/about-us, so instead of showing them a 404 page how about taking the web address they’ve typed in, assessing which page they might actually be trying to get to and then redirecting them to it. So, even when your user types in /aboutus.html they are taken to /about-us by the site. This makes for a much better user experience.

Now, I did say the example is a simple one, since the user even when hitting a 404 can still use the top-level navigation of your site to find the correct About Us page.

However, say your site has undergone a restructure e.g. it may have a been a static site and it now sits on a CMS that forces a particular url structure that your site did not previously observe, or indeed the site has moved from one CMS to another. If you have a well established online brand then there may be a number of emails and other web sites that carry old links to your site, links still utilising the old structure. So we want a way to map the old site links to the new site links, so that an old url called is automatically redirected to its newer format, so a user never doesn’t see a frustrating 404 page.

This problem is easily solved when using open source content management systems like WordPress, which has a number of redirect plugins that make adding this functionality to your website simple.

One such plugin of which have some experience is Redirection for WordPress. This is a powerful plugin that allows you to set up custom redirects, to set auto-redirects so the user is sent to the closest matching url, and it logs 404 errors to help set up those custom redirects. It’s free and worth checking out if you’re in the market to improve your user experience and help visitors find information on your site rather than hitting them with a frustrating 404, no matter how attractive.

Super yachts in Greece and Gordon Welchman, codebreaker

The blue water of the Mediterranean never fails to impress. Something else of note around the Greek islands on this cruise was the sheer number of yachts and super-yachts; these two super yachts were berthed at an island we sailed past after leaving Mykonos.

The second picture today is of some MEAN (MongoDB, Express.js, AngulasJS, Node.js) programming I was doing whilst watching a fascinating BBC documentary on Gordon Welchman, who along with Alan Turing, broke the Nazi Enigma cypher code, shortening the war by two years and saving hundreds of thousands, if not millions, of lives in the process. If you’ve never heard of him don’t worry, not many have. After his stint at Bletchley Park Welchman went on to the US to help the NSA set up their operations and was therefore bound not only by the British Official Secrets Act but by the US Espionage Act.

Find me on Instagram here

Is your WordPress site slow? XML-RPC could be under attack!

Recently, a WordPress site I manage was having serious downtime issues. Calling the site from a browser resulted in a lag time of many minutes!

Upon looking at the running processes on the server, the list contained multiple Apache processes, around 20, all running at around 20MB each. The maths comes in at 400MB of RAM being used for the the Apache processes and that was resulting in all the allocated server RAM, as well as 100% of the CPU, being consumed. This meant no new client connections were served.

Multiple hard reboots of the server did not solve the problem. The Apache processes were back almost as soon as the server came back up. This was fishy as that meant the connections were sustained in some manner.

On further inspection it appeared that 18 of the Apache processes were connections from a single IP address and they were all requesting a single file – xmlrpc.php

As it happens this is quite a popular way to attack a website and crash it. Although I’m still looking for a long-term solution, in the short term I’ve blocked that IP. Another way to safeguard your site is to control access to xmlrpc.php via your .htaccess file. However take care with this file as it can prove to be quite useful. More here – https://wordpress.org/support/topic/what-is-xml-rpc-good-for

I’ll post more when I have a real solution.

Update: The WordFence site has some more information on XML-RPC as a security risk and how to disable it.

jQuery for responsive image maps and time in the new garden fort

Spent some time working with the rwdImageMaps jQuery plugin for implementing responsive image maps as well as the qTip2 jQuery plugin for rich tool tips for responsive image maps. Coding is always so much fun!

Spent some time with my son in the new garden fort – a lovely summer day not to be wasted!

Find me on Instagram here

Javascript query string manipulation & a direwolf Game of Thrones t-shirt!

Some front-end development today using Javascript to manipulate query strings for a WordPress template. Good fun all round!

A lovely Father’s Day gift from my sons – a t-shirt depicting the sigil of my favourite family in Game of Thrones: The direwolf head of the Stark family.

Find me on Instagram here

Coder + Raspberry Pi = Cheap, Safe Web Development Platform

Over the last 12 months or so there has been a real push in education to get more adults and kids coding, or at least to understand the fundamentals of coding. I won’t discuss the merits of such a drive in this post, but I will say that coding is the future.

In order to contribute to this technology renaissance, Google’s Creative Lab has released ‘Coder‘, free software that turns a Raspberry Pi into a web platform with a code editor, enabling the user to try their hand at coding HTML, CSS and Javascript using the on board browser.

What makes this appealing is that all that is required is a Raspberry Pi which retails for about £40, allowing parents to set their kids up with a learning and development platform for programming  for very little money, and the payback can be enormous. There is little need, at least at the early stages, to even connect to the Internet, keeping the learning environment safe.

Check out more about Coder & the Raspberry Pi below…

[youtube_video id=”wH24YwdayFg” width=”600″ height=”400″]

Responsive Screen Layout Using JavaScript & CSS

Working on a new version of the website for The Corporate IT Forum, it became obvious that an adaptive/responsive screen layout would be beneficial for our site users. Usage stats confirmed that a number of different screen resolutions were in use in accessing the site and of course newer devices too i.e. tablets & pads.

CSS Fluid Layout

The new site layout required three columns with the left & right columns at a fixed width and the center column fluid. To adhere to SEO best practice, it was important that the center column, which houses the main content, appear above the two side columns for when the search engine spiders came to visit.

We also wanted to be sure that it was a robust CSS layout – to that end, the 3-column liquid layout by Matthew James Taylor came to the rescue.

Screen Resolution Breakpoints

The site is quite modular and we wanted to be smart with the presentation of multiple content modules in the center column i.e. three modules to a row if the screen resolution is ‘x’ or drop to two wider modules if the resolution is ‘y’.
The modules are styled to float left so they line up in a row across the screen, with a right-margin to set them apart from one another.
So, the next step was to identify the different screen resolution breakpoints – what resolution would require a change to the layout – and came up with the following:

  1. less than 1024
  2. between 1024  & 1366
  3. between 1366  & 1400
  4. between 1400  & 1440
  5. between 1440  & 1600
  6. between 1600  & 1680
  7. more than 1680

The JavaScript

Now that we had the breakpoints, it was time to assign each module with a suitable width on the fly, based on the user’s screen resolution, so that there would be as little space wasted as possible.

To use the DOM’s getElementById method, we had to assign each module a unique id. So each module was assigned the value “dynamicWidthModule” appended with a number as the unique identifier, so the first module was “dynamicWidthModule0”, the second “dynamicWidthModule1″ and so on.
We did this so ‘n’ number of modules can be generated, e.g. when using a CMS, where there is no opportunity to assign identifiers manually, and they can all be adjusted.

First then, before applying any function, we have to detect the user’s screen resolution which easily be done using

[codesyntax lang=”javascript” title=”Detect screen width” blockstate=”expanded”]

var clientWidth = screen.width;

[/codesyntax]

Next, based on the screen width breakpoints, set the module width and determine the number of modules per row (as explained earlier, because we’re using CSS float and margin to site the modules in a row, it is important to set the margin-right of the right-most module to zero)

[codesyntax lang=”javascript” title=”Determine module width & number of columns” blockstate=”expanded”]

if(clientWidth < 1024) { var setWidth = "350px"; } 
	else if (clientWidth >= 1024 && clientWidth < 1366) { var setWidth = "350px"; var col = 2; } 
	else if (clientWidth >= 1366 && clientWidth < 1400) { var setWidth = "393px"; var col = 2; } 
	else if (clientWidth >= 1400 && clientWidth < 1440) { var setWidth = "410px"; var col = 2; } 
	else if (clientWidth >= 1440 && clientWidth < 1600) { var setWidth = "430px"; var col = 3; } 
	else if (clientWidth >= 1600 && clientWidth < 1680) { var setWidth = "336px"; var col = 3; } 
	else if (clientWidth >= 1680) { var setWidth = "363px"; var col = 3;}

[/codesyntax]

Now, for each of the modules with the correct id, set the width and based on the number of modules per row, work out which modules should have a zero right margin.

[codesyntax lang=”javascript” title=”Set each module width & adjust right-margin if needed” blockstate=”expanded”]

var idMod = 0;
	while(document.getElementById(baseIdentifier + idMod)) 
	{
		document.getElementById(baseIdentifier + idMod).style.width = setWidth;

		if ( ( (col == 2 ) && (is_int((idMod + 1) / 2)) ) || ( (col == 3) && (is_int((idMod + 1) / 3)) ) ) {
			document.getElementById(baseIdentifier + idMod).style.marginRight = "0px";
		}

		idMod++;
	}

[/codesyntax]

Finally wrap it all up in a function and call it at the bottom of your page, or on DOMReady once all the elements are ready on the page

[codesyntax lang=”javascript” title=”The function & how to call it” blockstate=”expanded”]

function dynamicWidth(baseIdentifier) 
{
	var clientWidth = screen.width;

	if(clientWidth < 1024) { var setWidth = "350px"; } 
	else if (clientWidth >= 1024 && clientWidth < 1366) { var setWidth = "350px"; var col = 2; } 
	else if (clientWidth >= 1366 && clientWidth < 1400) { var setWidth = "393px"; var col = 2; } 
	else if (clientWidth >= 1400 && clientWidth < 1440) { var setWidth = "410px"; var col = 2; } 
	else if (clientWidth >= 1440 && clientWidth < 1600) { var setWidth = "430px"; var col = 3; } 
	else if (clientWidth >= 1600 && clientWidth < 1680) { var setWidth = "336px"; var col = 3; } 
	else if (clientWidth >= 1680) { var setWidth = "363px"; var col = 3;}

	var idMod = 0;
	while(document.getElementById(baseIdentifier + idMod)) 
	{
		document.getElementById(baseIdentifier + idMod).style.width = setWidth;

		if ( ( (col == 2 ) && (is_int((idMod + 1) / 2)) ) || ( (col == 3) && (is_int((idMod + 1) / 3)) ) ) {
			document.getElementById(baseIdentifier + idMod).style.marginRight = "0px";
		}

		idMod++;
	}
}

dynamicWidth("dynamicWidthModule");

[/codesyntax]

So, this little JavaScript & CSS combo allows the site to be viewed on most resolutions and the modules lay out accordingly.

Note : to determine the width of modules, you first need to calculate how many modules you want to fit in the center column, the width of which needs to be calculated by subtracting the total width of the fixed-width side columns as well as any padding.

Using an inline CSS style to create a new page in a PDF generator

I’ve recently been working with the TCPDF PDF generator class in PHP to generate PDFs on the fly as part of one of our newer business processes.

The class takes a lump of formatted HTML and creates a PDF document however generation being on the fly, there is no opportunity to use the inbuilt addpage() method of the class when the document needs to be broken up into multiple pages. A good example would be when generating an invoice and attaching a second page containing terms or a new chapter in a book.

Ideally, some marker within the HTML would inform the PDF generator when there is a page break, and thankfully there is.

Enter CSS

Set style="page-break-after:always;"

in the html e.g. for an empty div or p element, wherever you require a page break and TCPDF, and I warrant any good PDF generator function or class, will do the needful.

It’s handy to keep in mind that the same CSS style will also cause a printer to begin printing a new page when encountered.

Many thanks to Peter Young for this useful nugget.

Joomla : Fixing the User Password Reset Feature

Recently on one of my Joomla projects a user complained that they used the Password Reset feature but they encountered an error in the final steps of the process.

How does Joomla’s Password Reset feature work?

Joomla’s Password Reset feature asks for the user’s email address which it checks for in the user account table against that user’s record.

If found a unique token (a long series of numbers & characters) is generated and this is sent to the email address with a link back to the correct page on the website where the token needs to be entered to complete the process and allow the user to reset their password.

What went wrong?

Unfortunately, the email sent to the user displays the token in this manner :

The token is 408ebfa6c89glda0d267543e07a4cdeb4 .

Notice the space before the period? Well, understandably, the user was copying everything upto the preiod, including the space and pasting it into the field provided on the website for the final step. Unfortunately, that extra space counts as a character and so the token did not match and the user received an error and was unable to complete the reset. Not good.

The fixes

There are two fixes for this issue:

  1. Format the email properly so there is less of a chance of user error;
  2. Run the submitted token through PHP’s trim() function to strip out empty characters on either side of the token.

Making these two fixes should prevent this error occurring again and keep users who need to reset their passwords from becoming frustrated.

How to?

Format the email to remove the space

The first step requires us to amend the email that is sent out to the user. Joomla uses language files so it’s quite easy to amend this message. The reset password function is a part of the User Component in Joomla (com_user) so look up the correct file in the ‘language’ folder/directory :

/WEBROOT/language/en-GB/en-GB.com_user.ini

Search for this text “PASSWORD_RESET_CONFIRMATION_EMAIL_TEXT”  and edit the value of this setting by removing the space and period. I added newlines (n) before and after the token (%s) so that the token displays on a line by itself.

This has two advantages:

  1. Makes it clearer to the user if the token is on a line by itself
  2. Reduces the chance of user error when copying/pasting

Use trim() to remove whitespace

The second fix is the better one as it tackles the actual issue of readying the submitted token for comparison and matching.

In order to do this go to the following file :

/WEBROOT/components/com_user/models/reset.php

Search for the text “function confirmReset($token)” and inside this function add the trim function like so:

function confirmReset($token)
{
global $mainframe;

$token = trim($token);

……….. function continues ………..

}

This will now remove all extra whitespace on either side of the token submitted by the user so that the ‘clean’ token is used for comparison.

And that’s it – you will now have a sturdier Reset Password feature in Joomla.

Keep your WordPress site secure

wp-logo-blue-150x150More and more websites are using WordPress as their back-end Content Management System due to its ease of use and excellent built-in search-engine-optimization.

However, as with all software, WordPress does have bugs that are exploited to wreak havoc on your site.

This blog article talks about upgrading your WordPress installation to ensure the latest security patches have been applied and of the latest WordPress vulnerability.

Create mockups using Pencil and Firefox

A screen mockup in under a minute with Pencil
A screen mockup in under a minute with Pencil

Prototyping is the method by which a designer/developer mocks up pages/screens for a web site or some piece of software, to help the design and development team visualize the product. Sketching out on a piece of paper is generally best as at this stage of development there are likely to be many changes and sketching on paper is quick and cheap.

However, if you need to create sketches that are a little more professional, e.g. for a presentation to the Board, then it helps to use a tool like Pencil, a plugin for Firefox, which allows you to build a prototype using actual screen elements e.g. buttons, text fields etc. Using it is dead simple and very quick – just drag and drop elements onto a canvas and edit the properties to suit. I made the one on the right in under a minute.

Get Pencil for Firefox here

Use hooks to customize your WordPress site

WordPress is a powerful publishing platform (this site uses itwp-logo-blue-150x150) and it seems to be going from strength to strength. This is partly due to the fact that WordPress is easy to hack i.e. it’s easy to re-write code to make the platform do what you want it to.

Hacking core files, however, is problematic as the hacks are overwritten whenever you upgrade to a newer version, something that you need to do fairly often due to security holes being found and plugged and new features being introduced.

To overcome this problem, read this Smashing Magazine article on ‘hooks’ and how they can be used to provide you with powerful tools to customize your WordPress site.

RokDownloads – great Joomla Component for File Download Management

Over the last few weeks I’ve gotten increasingly busy (hence the lull in articles on this site) in customising certain Joomla components at work.

One component I came across just last week is RokDownloads. This is a file-download management component for Joomla 1.5 and as the name suggests it rocks! Developed by the same team that create the brilliant templates for Joomla, RocketWerx (RocketTheme) I guess it’s not that much of a surprise what a quality component this is.

I was using a popular component called DOCman however when it came to customising, it proved pretty difficult mostly due to the fact that it had first been developed for Joomla 1.0x and the team that created it only ported it to work in Joomla 1.5 Legacy Mode; meaning basically that they hadn’t really used the MVC (Model, View, Controller) protocol the way it’s used for Joomla 1.5 Native components.

RokDownloads is proving much easier to customise and even if you don’t need any customisation it just works really well.

So, if you’re looking for a great, free file-download manager hit up RokDownloads.

Joomla 1.0x Developers Manual

Although Joomla is a very popular open source application for building content-rich web sites, the available documentation for version 1.0x leaves a lot to be desired.

Currently working on a pretty big, and complicated, project involving multiple Joomla sites, I went off in search of relevant material that would help me design and build custom components and modules for version 1.015.

Unfortunately, I couldn’t find any single document that provided me with the information I needed, that is until I happened on a post on the Joomla Forum where someone had helpfully posted a link to a PDF of the Joomla Developers Manual.

Now, this guide for version 1.0x is incomplete, and will remain ever so since the Joomla Documentation Team are concentrating on getting a comprehensive Joomla 1.5 guide ready, however it does offer a lot of important information that you’ll only otherwise get by spending hours on the Joomla Forum and on other sites trying out tutorials.

So, if you’re looking for a ,somewhat, single document in PDF format that can help you understand the Joomla CMS engine a little better and help in building your own components and modules, look no further – click here to download the Joomla Developers Manual.

Cheat Sheets for PHP, Ruby on Rails, MySQL, CSS and SEO

I went on a bit of a Cheat Sheet binge this month. Working on a couple of projects using various technologies means I keep bouncing around looking for stuff so I thought I’d better get some cheat sheets up on my wall to save me time.

Most of these are from one site, the brilliantly named “ILoveJackDaniels” by UK web developer Dave Child:

  1. Ruby on Rails Cheat Sheet
  2. PHP Cheat Sheet
  3. MySQL Cheat Sheet
  4. CSS Cheat Sheet and more from the same site
  5. The Web Developers SEO Cheat Sheet by Danny Dover of SEOmoz.org 
  6. Conversion table for em, px, pt & % in CSS by Suresh Jain

Ruby and PHP are the Leading Web Development Languages according to Sun’s Tim Bray

Tim Bray, director of Web Technologies at Sun Microsystems, said in April’s Ruby Conference that Ruby and PHP are the languages of choice for new web applications.

Both Ruby and PHP are open source and therefore it comes as no surprise that both these languages are being taken up far more quickly than established languages like Java.

There are other factors too; One of the main ones is that many new web applications need to reach their market as quickly as possible. Applications developed in compiled languages like Java cannot be rolled out iteratively as compared to those developed using interpreted scripting languages like Ruby or PHP making them far less desirable.

There are also quite a few web development frameworks built on these two languages around now, Rails based on Ruby and Symfony based on PHP are two that I know of. This makes it even faster, and easier, to develop and deploy a new web application.

Find out more about:

Joomla – the difference between components and modules

When starting out in Joomla, either as a developer or site administrator, it’s likely one of the first questions to pop up will be what the difference between a Component and a Module is. Although it’s possible to ‘figure’ out what does what, it’s always a good idea to get the low-down from someone who’s experienced in Joomla development.

Joseph LeBlanc has a great article on his site making it very simple to understand the main differences