Category Archives: medium

Open Comment Author link in new window

I’ve been searching for a way to open a commenter link on a new window for a long time and with no success. Most of the techniques required me to open one of wordpress core files and alter its functions. Thought it did work, the changes were doom to vanish on the next upgrade.

The correct way to do that is to use the built-in hook system in order to alter the link after it was created.

add_filter('get_comment_author_link', 'authorLinkNew');
function authorLinkNew($result){
	return str_replace ('<a', '<a target="_blank" ', $result);
}

Actually all we do here is search and replace on the anchor element and in that way to add the target blank into the link. It’s actually a bit rough, and there must be a dozen of different ways to do it which are more correct (using php domelement would probably be the best one, Using Regex with preg_replace may be another) but it’s surely the fastest way to do that.
Please note that using another plugin that rewrite links might cause a collision that way, and rewrite this function using a domelement will return better results.

Simple file based caching system

Once in a time I need one of my sites to grab a RSS feed, parse it and display its results in the page. The main problem is that the processing takes a lot of time (and resources) which intemperate to a large delay on the client side.

This is also quite a silly thing to do due to the fact that unless its your twitter feed it usually doesn’t update so frequently.

So we want to cache the whole process in order to save time and resources and usually it’s been done by saving the feed locally and parsing it from the server. Though it shorts the grabbing time we still need to parse it again and again.

Cache the results
Instead of saving the feed a better way would be to save the parsing results, thus we only serve a text file that is on our server – which is always a lot faster.

The Idea is to have a function that looks for the cache file, if it finds it, the file content will be included, if not, the function will parse the feed and create a new cache file.

function getdatacache(){
$fileName = 'content.cache';
$file = 'cache/'.$fileName;
if (@file_exists($file))
{
$content = file_get_contents($file);
} else {
$content = parseTheFeed();
file_put_contents($file, $content);
}
return $content;
}

So, we set the file name, look for that file and if it exists we takes its content. Else we parse the feed (parseTheFeed is the function that does the actual parsing) and save the result (The function should return a string or to use output buffering ob-start – http://php.net/manual/en/function.ob-start.php).

What about Time To Live (TTL)?

Unless we want a one time only feed parsing (and what would be the point in that?) we need a TTL system. One way is to run a cron job on the cache folder that will delete files older than the required TTL. It can work but only if you’re hosting supplier supports cron jobs.
Instead of deleting files, we can set the TTL using php date function as the file name.
Instead of $fileName = ‘content.cache’; we can use
$fileName = date(‘H’).’.cache’;

With that change the script will create a new file every hour and save it to the cache folder. Although the first user in every hour will have a delay the system will be much faster for every user after that.

In order to prevent that from happening one can run a script on the last-minute of the hour that will create the next hour cache it can be done using a boolean switch and a separate call from the end of our script or by a different script called by a cron job.

 function getdatacache($nextHour = false){
if($nextHour &amp;&amp; date('i')&gt;=57)
$fileName = (date('H')+1). '.cache';
else
$fileName = date('H').'.cache';
$file = 'cache/'.$fileName;
if (@file_exists($file))
{
$content = file_get_contents($file);
} else {
$content = parseTheFeed();
file_put_contents($file, $content);
}
return $content;
}

Note
Bare in mind that in order for this script to run properly, the cache folder should have write permissions.

Customizing the look and feel of your sidebar widgets

Every now and then, you realize that you might not have been doing something wrong, but you’ve been working hard and stupidly. One of these revelations was figuring out just how simple it is to customize the different types of sidebar widgets without some serious fumbling around.

Sure, you could work extra hard to re-create the entire sidebar via code, so everything there is perfect and beautifully designed, but at the same time, the widgetized sidebar is no longer functional, which makes this not only extra work, but also a rather lame solution.

The smart alternative is using the unique class names which WordPress (or any widgety plugin) assigns to the various widget types. Just because the template we’re working on doesn’t contain styling for these elements doesn’t mean that we can’t do that ourselves!

For example, if we want to decorate the Search box or the categories, we can simply create styling for the built-in widget_search or widget_categories, and voila!

Of course, you mustn’t forget to also create a generic design that can style any widgets that might be added in the future, or your clients might find themselves wondering why the hell that newfangled box they added themselves looks like crap.

Excerpts the right way

As of WordPress 2.9 there are 2 new filters that helps us control the excerpts look&feel.

These two filters are:

  • excerpt_more – lest us define the excerpt trailing character
  • excerpt_length – lets us define the excerpt length (in words)

These functions ease the modification of WordPress excerpts for custom-made themes.

Here is example for using them:

Make wordpress mail you on 404 errors

One of the problematic black holes in a website is the 404 error page, and while the uninformative ones may look nice, they are usually the worst. The main cause for a 404 page is that we, as editors, broke something; and the main problem is that we usually won’t notice that.

The 404 event is usually logged in the Apache log, a log most of us never bother looking at, not to mention, never bother looking after – so if you changed something, you’ll probably won’t know about it for a long time.

The next tip I learned from Milo317 who solved  my question with a nice and elegant answer – Well, why not tell WordPress to email you whenever that happens?

$adminemail = get_bloginfo('admin_email');
$website = get_bloginfo('url');
$websitename = get_bloginfo('url');
if (!isset($_SERVER['HTTP_REFERER']))
echo "Seems like you have done something that's uncool, because we can't find whatever you are after";
elseif (isset($_SERVER['HTTP_REFERER'])){
$failuremess = "A user tried to go to $website" .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
$failuremess .= "It wasn't their fault, so try fixing it. They came from ".$_SERVER['HTTP_REFERER'];
mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
$failuremess, "From: $websitename &lt;noreply@$website&gt;"); }

The code is pretty straight forward – WordPress grabs the admin’s email and the blog details and checks if the user got to that page by referal or by mistake (wrong copy-paste for example).

If there was a reference to that page, WordPress will generate an email message with all the relevant details and send it to the admin. Setting a 301 (moved permanently) reference will usually solve most of these problems.

Custom header image

WordPress custom header image API gives blog administrator the ability to control and change the header design (image and font color).
This functionality is very easy to add and use, and upgrades the theme usability significantly.
The interface is added to the Appearance menu.

And looks like this:

The code bits are pretty simple:
Assumin the header part lookis like this:
[cc lang='php']


[/cc]

We need to add 3 different secions to out function.php

  1. Default values definition – text color, background image, image width, image height
  2. The API callback function – functions that alter the header css upon activation. There are two such functions:
    • The function set as header_callback is called when displaying a specific blog page. It is activated by the action_hook wp_head
    • The function set as admin_header_callback is called when displaying administration panels
  3. Callback registration

The definitions code looks like this:
[cc lang='php']
// Set some default values
define('HEADER_TEXTCOLOR', 'fff'); // Default text color
define('HEADER_IMAGE', '%s/default.jpg'); // %s is theme dir uri, set a default image
define('HEADER_IMAGE_WIDTH', 500); // Default image width is actually the div's height
define('HEADER_IMAGE_HEIGHT', 150); // Same for height
?>
[/cc]

Once we’ve set the default values we can add the callback functions:
[cc lang='php']
function header_style() {
// You can change these selectors to match your theme
?>

}

// This function is not relevant unless you want your admin
// header to be changed as well... You can leave it empty
function admin_header_style() {
// This function styles the admin page
?>

}
?>
[/cc]

Now we just need to register the callbacks:
[cc lang="php"]
add_custom_image_header('header_style', 'admin_header_style');
?>
[/cc]

Note that this API is activated by calling wp_head() so if your function does not have that function call in header.php you should add it.
In oredr to add wp_head to your header you need to add the following line just before the body tab:
[cc lang="php"][/cc]