5 essential tips for a better website in 2016

Make it fast!

It’s a known fact that Internet users don’t like to wait. If your website fails to load quickly enough, most potential visitors will close the page and visit another site instead. Adding to that, Google announced last year that loading time has a huge impact on how they rank websites.

So if you want your website to be better in 2016, speed is among the most crucial things to consider. Get a fast host, use caching, minify HTML, JavaScript and CSS, use a CDN, minimize HTTP requests. Everything you need to know is explained in the article linked below.

optimize your images

Images are always an important part of a website. Images also tend to be huge and consequently take forever to load and use a lot of bandwidth. Did you know that with a few tools and a little of knowledge you can make your website way faster to load and save some precious bandwidth?

Image optimization can be summed up in the following: choosing the right format and size, using images only when needed, and find the right balance between quality and weight. Everything you need to know is explained in detail below.

Be mobile friendly

In recent years, mobile browsing has supplanted desktop browsing. In other words, it is now extremely important that you make sure that your website is 100% mobile ready.

A good example of mobile friendly web design is the Monte WordPress theme, created by WPzoom. Check it and resize your browser to see how well it displays under different resolutions.

Making a website responsive (i.e. fitting perfectly different screen resolutions) is easier than it seems, thanks to CSS media queries.

Use webfonts instead of icons

Using icon webfonts is super easy. The first thing to do is to download a font. In this example I’m using the amazing MFG Labs font that you can download for free here. Feel free to browse the collection linked below if you prefer to use another font.

Once done, upload the files on your webserver and add the downloaded stylesheet to your website. For better performance, I recommand that you copy/paste the content of the stylesheet into your website’s main style.css file.

And finally, you simply have to drop the markup in your html file. Below is an example of creating two icons with links to my Twitter and Facebook profiles.

<a href="https://twitter.com/catswhocode"><i class="icon-twitter_circle icon2x"></i></a>
<a href="https://www.facebook.com/catswhocode"><i class="icon-facebook_cricle icon2x"></i></a>

Switch to a quality host

There’s no quality website without a quality server. If you want your website to be fast and available 24/7, you have to consider using the services of a quality hosting provider. Below is the list of my three personal favorites:

Vidahost: this company has been hosting CatsWhoCode since 2012. The speed and availability are amazing and the support service always responds fast, even on Sundays or in the middle of the night. The only downpoint is the somewhat expensive price, but just like cheap hosting isn’t good, good hosting isn’t cheap.
Good news: by using the coupon CATSWHOCODE when checking out, you’ll get 10% off any hosting plan.

A Small Orange: A company I work with, as well as many of my partners. A Small Orange is offering an exclusive discount to CWC readers consisting of one year of hosting + a domain name for only $40. Definitely a great deal for serious websites owners.

In Motion Hosting: I haven’t worked with them directly yet, but I’ve been fixing quite a lot of websites hosted on their servers and everything was smooth. Definitely worth checking!

That’s all for today! I wish you all a super happy 2016 and a lot of fun making/enhancing websites!

Downsize your WordPress database by removing transients

First of it all, login to your phpmyadmin and choose your WordPress database. Once done, click on the sql button to open the sql command window.
Then, simply paste the following sql command and execute it.

DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%');

Credit: Stack Overflow

Want more super useful SQL queries? Check out this article on Cats Who Code.

The post Downsize your WordPress database by removing transients appeared first on WPRecipes.

Downsize your WordPress database by removing transients

First of it all, login to your phpmyadmin and choose your WordPress database. Once done, click on the sql button to open the sql command window.
Then, simply paste the following sql command and execute it.

DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%');

Credit: Stack Overflow

Want more super useful SQL queries? Check out this article on Cats Who Code.

The post Downsize your WordPress database by removing transients appeared first on WPRecipes.

Downsize your WordPress database by removing transients

First of it all, login to your phpmyadmin and choose your WordPress database. Once done, click on the sql button to open the sql command window.
Then, simply paste the following sql command and execute it.

DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%');

Credit: Stack Overflow

Want more super useful SQL queries? Check out this article on Cats Who Code.

Using SQL to manage WordPress: The definitive guide

Before getting started

There are several ways to run SQL queries. Most of you probably have a cPanel installed on your server. This is the case if your host is Vidahost, A Small Orange or In Motion Hosting, for example.

To access phpMyAdmin from cPanel, simply log in to cPanel and click the phpMyAdmin icon in the Databases section.

Once you’ve entered PhpMyAdmin, you first have to select your blog database, then click on SQL tab to display the page which allows you to run any kind of queries.

Another option is to use a plugin named SQL Executioner. As the name says, the aim of this plugin is to allow you to run SQL queries on your WordPress database from within the Dashboard.

Important things to note:

  • Always have a fresh backup of your database when applying those SQL queries. You can do so manually or use a WordPress plugin such as WP-DBManager.
  • This article uses default table prefix wp_. Make sure you change the prefixes to match the ones used by your database.

Delete all comments with a specific url

Spam is definitely a problem ith WordPress blogs, happily SQL is here to help.

DELETE from wp_comments WHERE comment_author_url LIKE "%spamurl%" ;

Source: WPRecipes

Delete all trackbacks

Most people, including me, think that trackbacks are useless. Clean up your blog database with that nifty query.

DELETE FROM wp_comments WHERE comment_type="trackback";

Source: WordPress.org Forums

Close trackbacks on all posts at once

Even better than deleting them, you can close all trackbacks at once with this query.

UPDATE wp_posts SET ping_status = 'closed';

Source: Dig WP

Bulk delete all unapproved comments

Too lazy to check all of your unapproved comments? This is the super fast way to delete them all at once.

DELETE from wp_comments WHERE comment_approved = '0';

Source: WordPress.org Forums

Bulk delete all comments marked as spam

Got 5400 spam comments and don’t want to go through dozen of pages to delete them? This query is for you.

DELETE FROM wp_comments WHERE wp_comments.comment_approved = 'spam';

Source: Dig WP

Delete all post revisions and associated data

Make your database lighter by removing post revisions and all associated data. A query I run on my blogs every 3-6 months.

DELETE a,b,c FROM wp_posts a LEFT JOIN wp_term_relationships b ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c ON (a.ID = c.post_id) WHERE a.post_type = 'revision';

Source: Solidly Stated

Remove unused shortcodes in post content

Shortcodes are really cool, but at some point you need to be able to remove the unused ones. Rather than editing each of your posts, run this simple query! Replace [tweet] by the unused shortcode to remove.

UPDATE wp_post SET post_content = replace(post_content, '[tweet]', '' ) ;

Source: WPRecipes

Replace a word by another in post content

This can be very useful to update a link, for example.

UPDATE wp_post SET post_content = replace(post_content, 'old_word', 'new_word' ) ;

Add a custom field to all posts

If you’re always using a specific custom field, you better add it on all posts at once rather than editing X amount of your posts. Here you go!

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'MyCustomField'
AS meta_key 'myvalue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'MyCustomField')
`` AND post_type = 'post';

Source: The Customize Windows

Delete very old posts

Are all your posts very outdated? Here’s an easy way to remove them. For optimal results, you should definitely use 301 redirections to redirect deleted posts to your homepage or updated versions of those posts.

DELETE FROM wp_posts WHERE post_date < '2010-01-01 00:00:00' AND post_status = 'publish'

Source: xarj.net

Get a list of all commentators’ emails

Not really that you should use email of your commentators for anything (except with their consent) but here’s the way to get a list of all emails stored in the wp_comments table. Note the use of DISTINCT to make sure the query won’t return any duplicates.

SELECT DISTINCT comment_author_email FROM wp_comments;

Source: Dig WP

Assign posts to a new author

If for some reason you want to transfer posts from an author to another, this query is yours. You need to update this query with both the old author and new author IDs before running it.

UPDATE wp_posts SET post_author = 'new-author-id' WHERE post_author = 'old-author-id';

Source: WPRecipes

Update user password

Quick way to update any password. Don’t forget to replace username by the user name of the user you’d like to update the password.

UPDATE wp_users SET user_pass = MD5( 'new_password' ) WHERE user_login = 'username';

Source: WordPress Support

Batch disable all plugins

In case something goes wrong with your blog, it can be a good idea to deactivate all your plugins, in case one of those was the source of the problem. Here’s how you can batch disable them using a SQL query.

UPDATE wp_options SET option_value = '' WHERE option_name = 'active_plugins';

Source: WPRecipes

Downsize your database by removing transients

Transients are a simple and standardized way of temporarily storing cached data in the database by giving it a custom name and a timeframe after which it will expire and be deleted. But sometimes, transients set by WP and countless plugins can take a lot of space in your database. Good news, transients can be safely removed with this simple query.

For more information about Transients, check out the Codex.

DELETE FROM `wp_options` WHERE `option_name` LIKE ('%\_transient\_%');

Source: Stack Overflow

Get rid of unused tags

As your database is probably filled with lots of tags you don’t use anymore, you should consider cleaning it with the following:

DELETE FROM wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id = wtt.term_id WHERE wtt.taxonomy = 'post_tag' AND wtt.count = 0;

Source: WPMU Dev

Change all your urls/domain names

WordPress stores absolute urls within the database. Which means that if you change your blog domain name, you’ll have to update every absolute url. Using SQL, this is extremelly simple to do. Just edit the three queries below and update the old and new domain names, then run it. Done!

UPDATE wp_options SET option_value = replace(option_value, 'http://www.oldsite.com', 'http://www.newsite.com') WHERE option_name = 'home' OR option_name = 'siteurl';
UPDATE wp_posts SET guid = replace(guid, 'http://www.oldsite.com','http://www.newsite.com');
UPDATE wp_posts SET post_content = replace(post_content, 'http://www.oldsite.com', 'http://www.newsite.com');

Source: Smashing Magazine

The Core:­ A massive multi­purpose theme review and giveaway

Introducing “The Core”

All the demos that comes with The Core theme are not just slight alterations of the same theme but actually complex themes on their own, created for food blogs, personal blogs, educational blogs, design blogs and many other awesome blog and magazine style websites.

The Core WordPress theme, which is built on the the Unyson framework, includes lots of cool features like a powerful visual page builder, unlimited color palette options, a set of ready to use shortcodes, a backup up module, over 700 fonts, multiple headers, footers and sliders, demo content install, extensive documentation and much more.

The Core comes with a powerful visual page builder that helps you to create countless pages in a matter of clicks and drags. Only drag and drop the design elements on the canvas and create a perfect feel for your website. This theme is also optimized for a Responsive & Retina experience, so it is fully responsive and mobile friendly.

Moreover the Content Demo Install feature makes you sure to keep the same look and style for theme as the one you see on our Live Demo. The theme is also ecommerce ready thanks to its built in WooCommerce support. With The Core you can definitely showcase your content with style, since it has a couple of awesome sliders: Slider Revolution (usually $19), Layers Slider (usually $18) and our own custom­built version of slider that allows uploading images and videos. Will also save $37 in the process since the Revolution and Layers sliders come included free of charge.

The Core is $59 and counting the 10 incorporated demos that you’ll get all and the additional new demos for free, this theme is a perfect deal.

Take a look at this Video to see an overview of this great theme:

The Giveaway

You have the opportunity to win a subscription for The Core WordPress Theme. Be the lucky one and follow the three steps below to take part in this contest:

Next week, the lucky winner will be chosen and will receivehis theme directly from ThemeFuse.
Best of luck!

WordPress tip: move all JavaScript files to the footer automatically

First, open your functions.php file and paste the following code in it:

/**
 * Filter HTML code and leave allowed/disallowed tags only
 *
 * @param string 	$text 	Input HTML code.
 * @param string 	$tags 	Filtered tags.
 * @param bool 		$invert Define whether should leave or remove tags.
 * @return string Filtered tags
 */
function theme_strip_tags_content($text, $tags = '', $invert = false) {

    preg_match_all( '/<(.+?)[\s]*\/?[\s]*>/si', trim( $tags ), $tags );
    $tags = array_unique( $tags[1] );

    if ( is_array( $tags ) AND count( $tags ) > 0 ) {
        if ( false == $invert ) {
            return preg_replace( '@<(?!(?:'. implode( '|', $tags ) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text );
        }
        else {
            return preg_replace( '@<('. implode( '|', $tags ) .')\b.*?>.*?</\1>@si', '', $text );
        }
    }
    elseif ( false == $invert ) {
        return preg_replace( '@<(\w+)\b.*?>.*?</\1>@si', '', $text );
    }

    return $text;
}

/**
 * Generate script tags from given source code
 *
 * @param string $source HTML code.
 * @return string Filtered HTML code with script tags only
 */
function theme_insert_js($source) {

    $out = '';

    $fragment = new DOMDocument();
    $fragment->loadHTML( $source );

    $xp = new DOMXPath( $fragment );
    $result = $xp->query( '//script' );

    $scripts = array();
    $scripts_src = array();
    foreach ( $result as $key => $el ) {
        $src = $result->item( $key )->attributes->getNamedItem( 'src' )->value;
        if ( ! empty( $src ) ) {
            $scripts_src[] = $src;
        } else {
            $type = $result->item( $key )->attributes->getNamedItem( 'type' )->value;
            if ( empty( $type ) ) {
                $type = 'text/javascript';
            }

            $scripts[$type][] = $el->nodeValue;
        }
    }

    //used by inline code and rich snippets type like application/ld+json
    foreach ( $scripts as $key => $value ) {
        $out .= '<script type="'.$key.'">';

        foreach ( $value as $keyC => $valueC ) {
            $out .= "\n".$valueC;
        }

        $out .= '</script>';
    }

    //external script
    foreach ( $scripts_src as $value ) {
        $out .= '<script src="'.$value.'"></script>';
    }

    return $out;
}

Once done, edit your header.php file. Replace the wp_head() tag by this:

<?php
ob_start();
wp_head();
$themeHead = ob_get_contents();
ob_end_clean();
define( 'HEAD_CONTENT', $themeHead );

$allowedTags = '<style><link><meta><title>';
print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );
?>

And finally, place the code below into your footer.php file, just before the closing </body> tag.

<?php theme_insert_js( HEAD_CONTENT ); ?>

Credit: Tomasz Dobrynski.

For more information and tips about speeding up your WordPress blog, check out this article I wrote on Cats Who Code: Google PageSpeed Insights: How I fixed my slow website

The post WordPress tip: move all JavaScript files to the footer automatically appeared first on WPRecipes.

WordPress tip: move all JavaScript files to the footer automatically

First, open your functions.php file and paste the following code in it:

/**
 * Filter HTML code and leave allowed/disallowed tags only
 *
 * @param string 	$text 	Input HTML code.
 * @param string 	$tags 	Filtered tags.
 * @param bool 		$invert Define whether should leave or remove tags.
 * @return string Filtered tags
 */
function theme_strip_tags_content($text, $tags = '', $invert = false) {

    preg_match_all( '/<(.+?)[\s]*\/?[\s]*>/si', trim( $tags ), $tags );
    $tags = array_unique( $tags[1] );

    if ( is_array( $tags ) AND count( $tags ) > 0 ) {
        if ( false == $invert ) {
            return preg_replace( '@<(?!(?:'. implode( '|', $tags ) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text );
        }
        else {
            return preg_replace( '@<('. implode( '|', $tags ) .')\b.*?>.*?</\1>@si', '', $text );
        }
    }
    elseif ( false == $invert ) {
        return preg_replace( '@<(\w+)\b.*?>.*?</\1>@si', '', $text );
    }

    return $text;
}

/**
 * Generate script tags from given source code
 *
 * @param string $source HTML code.
 * @return string Filtered HTML code with script tags only
 */
function theme_insert_js($source) {

    $out = '';

    $fragment = new DOMDocument();
    $fragment->loadHTML( $source );

    $xp = new DOMXPath( $fragment );
    $result = $xp->query( '//script' );

    $scripts = array();
    $scripts_src = array();
    foreach ( $result as $key => $el ) {
        $src = $result->item( $key )->attributes->getNamedItem( 'src' )->value;
        if ( ! empty( $src ) ) {
            $scripts_src[] = $src;
        } else {
            $type = $result->item( $key )->attributes->getNamedItem( 'type' )->value;
            if ( empty( $type ) ) {
                $type = 'text/javascript';
            }

            $scripts[$type][] = $el->nodeValue;
        }
    }

    //used by inline code and rich snippets type like application/ld+json
    foreach ( $scripts as $key => $value ) {
        $out .= '<script type="'.$key.'">';

        foreach ( $value as $keyC => $valueC ) {
            $out .= "\n".$valueC;
        }

        $out .= '</script>';
    }

    //external script
    foreach ( $scripts_src as $value ) {
        $out .= '<script src="'.$value.'"></script>';
    }

    return $out;
}

Once done, edit your header.php file. Replace the wp_head() tag by this:

<?php
ob_start();
wp_head();
$themeHead = ob_get_contents();
ob_end_clean();
define( 'HEAD_CONTENT', $themeHead );

$allowedTags = '<style><link><meta><title>';
print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );
?>

And finally, place the code below into your footer.php file, just before the closing </body> tag.

<?php theme_insert_js( HEAD_CONTENT ); ?>

Credit: Tomasz Dobrynski.

For more information and tips about speeding up your WordPress blog, check out this article I wrote on Cats Who Code: Google PageSpeed Insights: How I fixed my slow website

The post WordPress tip: move all JavaScript files to the footer automatically appeared first on WPRecipes.

WordPress tip: move all JavaScript files to the footer automatically

First, open your functions.php file and paste the following code in it:

/**
 * Filter HTML code and leave allowed/disallowed tags only
 *
 * @param string 	$text 	Input HTML code.
 * @param string 	$tags 	Filtered tags.
 * @param bool 		$invert Define whether should leave or remove tags.
 * @return string Filtered tags
 */
function theme_strip_tags_content($text, $tags = '', $invert = false) {

    preg_match_all( '/<(.+?)[\s]*\/?[\s]*>/si', trim( $tags ), $tags );
    $tags = array_unique( $tags[1] );

    if ( is_array( $tags ) AND count( $tags ) > 0 ) {
        if ( false == $invert ) {
            return preg_replace( '@<(?!(?:'. implode( '|', $tags ) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text );
        }
        else {
            return preg_replace( '@<('. implode( '|', $tags ) .')\b.*?>.*?</\1>@si', '', $text );
        }
    }
    elseif ( false == $invert ) {
        return preg_replace( '@<(\w+)\b.*?>.*?</\1>@si', '', $text );
    }

    return $text;
}

/**
 * Generate script tags from given source code
 *
 * @param string $source HTML code.
 * @return string Filtered HTML code with script tags only
 */
function theme_insert_js($source) {

    $out = '';

    $fragment = new DOMDocument();
    $fragment->loadHTML( $source );

    $xp = new DOMXPath( $fragment );
    $result = $xp->query( '//script' );

    $scripts = array();
    $scripts_src = array();
    foreach ( $result as $key => $el ) {
        $src = $result->item( $key )->attributes->getNamedItem( 'src' )->value;
        if ( ! empty( $src ) ) {
            $scripts_src[] = $src;
        } else {
            $type = $result->item( $key )->attributes->getNamedItem( 'type' )->value;
            if ( empty( $type ) ) {
                $type = 'text/javascript';
            }

            $scripts[$type][] = $el->nodeValue;
        }
    }

    //used by inline code and rich snippets type like application/ld+json
    foreach ( $scripts as $key => $value ) {
        $out .= '<script type="'.$key.'">';

        foreach ( $value as $keyC => $valueC ) {
            $out .= "\n".$valueC;
        }

        $out .= '</script>';
    }

    //external script
    foreach ( $scripts_src as $value ) {
        $out .= '<script src="'.$value.'"></script>';
    }

    return $out;
}

Once done, edit your header.php file. Replace the wp_head() tag by this:

<?php
ob_start();
wp_head();
$themeHead = ob_get_contents();
ob_end_clean();
define( 'HEAD_CONTENT', $themeHead );

$allowedTags = '<style><link><meta><title>';
print theme_strip_tags_content( HEAD_CONTENT, $allowedTags );
?>

And finally, place the code below into your footer.php file, just before the closing </body> tag.

<?php theme_insert_js( HEAD_CONTENT ); ?>

Credit: Tomasz Dobrynski.

For more information and tips about speeding up your WordPress blog, check out this article I wrote on Cats Who Code: Google PageSpeed Insights: How I fixed my slow website

Detecting Adblock on your WordPress site

Disclaimer

Should you do something against people visiting your site with an ad blocker on? That’s the question many site owners are asking themselves since a few years.

Since the web exists, advertising has been a way for webmasters and site owners to make money. As ads brought lots of money, many people abused the model, displaying video ads, ads blocking contents, popups, etc. Even today, visiting a download site or just watching YouTube videos without an ad blocker is a complete pain. Approximately ten years ago, some people bothered by advertising abuse started to fight back. Ad blockers were born.

Some websites decide to do nothing against ad blockers. People who are using ad blockers aren’t likely to click on ads anyways, so it kinda makes sense. Other websites choose a diplomatic approach, asking their readers to whitelist their site, or make a small donation. And finally, some site owners choose to fight back against what they consider a threat to their revenue, by disabling features to readers who are using an ad blocker.

This article aims to demonstrate a few techniques which can be used to detect ad blockers or hide content from visitors with an ad blocker on. The way you use it on your website is up to you.

Basic JavaScript Adblock detection

The first thing to do is to create a file named adframe.js. This file is using the blacklisted name “adframe” so we’re gonna fool Adblock and make it block the file, mistaking it for a genuine ad. In the file, simply put the following line:

adblock = false;

Now, put the following withing the <head> and </head> tags of your HTML document.
On a WordPress Theme, the head section is displayed in header.php.

<script type="text/javascript">
    var adblock = true;
</script>
<script type="text/javascript" src="adframe.js"></script>
<script type="text/javascript">
    if(adblock) {
          //adblock is installed
    }
</script>

Hiding content from users with ad blockers on

Hiding content from users with an adblocker is definitely easy. The only thing you have to do is to pick up one class blocked by Adblock, and add it to the container of your choice.

In the example below I’ve used the class .bsarocks which is added by BuySellAds around their ad banners:

<div class="bsarocks">This won't be seen by Adblock users.</div>

WordPress plugin

While the code snippets shown above can definitely be useful, if you’re using WordPress, I definitely recommend using a plugin if you’re looking to detect/block Adblock. The main reason for favoring a plugin over a code snippet is that a plugin can be updated by its author as soon as there’s a change in the way Adblock works.

There’s a few plugins out here that specialize in Adblock (and other ad blockers) detection. The most interesting in my opinion is Ad Blocking Detector. Check out the demo on the plugin website. It detects ad blockers pretty well.

WordPress Ad Block Detector

Ad Blocking Detector gives you the availability to create shortcodes to display alternative content if an ad is blocked by an ad blocker. This is especially interesting if you want to encourage your readers to disable their adblocker on your website in order to support it.

The plugin should be installed through the basic plugin installation procedure, ie. “Plugins” → “Add New” in your WordPress dashboard.

Detecting visitors with JavaScript off

Some users also choose to disable JavaScript by default, to prevent many things such as popups being open, etc. Just in case you don’t know, there’s a HTML tag call noscript which allows you to display a message to users with JavaScript off:

<noscript>
 For full functionality of this site please enable JavaScript.
</noscript>

Which approach should you adopt?

Well, it’s up to you. I personally think that things aren’t all black or all white. Sure thing, ads are an important source of income for web publishers and many websites wouldn’t exist without them. On the other hand, some ads are so annoying that people who use an ad blocker can definitely be understood.

The only sure thing is that, as a website owner, you shouldn’t display “aggressive” ads to your visitors. Pop unders, video or flash ads, etc, in my opinion those should be totally banished from a serious and professional website. On the other hand, I have no problem with related banners ads, as such as the ones you can purchase on BuySellAds.com.

WordPress tip: How to display a disclaimer on posts older than one year

Paste the following code in your single.php file, within the loop. Edited the text on line 7 as desired.

<?
$ageunix = get_the_time('U');
$days_old_in_seconds = ((time() - $ageunix));
$days_old = (($days_old_in_seconds/86400));

if ($days_old > 365) {
  echo '<div class="disclaimer">DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.</div>'; 
} 
?>

The post WordPress tip: How to display a disclaimer on posts older than one year appeared first on WPRecipes.

WordPress tip: How to display a disclaimer on posts older than one year

Paste the following code in your single.php file, within the loop. Edited the text on line 7 as desired.

<?
$ageunix = get_the_time('U');
$days_old_in_seconds = ((time() - $ageunix));
$days_old = (($days_old_in_seconds/86400));

if ($days_old > 365) {
  echo '<div class="disclaimer">DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.</div>'; 
} 
?>

WordPress tip: How to display a disclaimer on posts older than one year

Paste the following code in your single.php file, within the loop. Edited the text on line 7 as desired.

<?
$ageunix = get_the_time('U');
$days_old_in_seconds = ((time() - $ageunix));
$days_old = (($days_old_in_seconds/86400));

if ($days_old > 365) {
  echo '<div class="disclaimer">DISCLAIMER: this post is older than one year and may not be up to date with latest WordPress version.</div>'; 
} 
?>

The post WordPress tip: How to display a disclaimer on posts older than one year appeared first on WPRecipes.

Google PageSpeed Insights: How I fixed my slow website

So… I headed to Google PageSpeed Insights and decided to check my website. The result wasn’t very pleasant, as you can see below. A grade of 58/100 and a red color, indicating poor speed optimization. Well, I had to do something!

Optimizing images

Images are a very important part of every website. Consequently, a website can be slowed down by too many, too big or mostly, badly optimized images. The first thing PageSpeed Insights gave me a warning about was that most of the images used on Cats Who Code were too big and poorly optimized.

How I fixed the problem: I used a free WordPress plugin called WP Smush. It has a super useful option which allows you to optimize all your attached images (There’s over 800 of them on the blog) in bulk of 50. It takes a while, but it’s worth it: I reduced my images of an average 20% while preserving a sufficient quality on all my pictures.

To do so, install WP Smush, then go to Media → WP Smush. Scroll down a little, and you’ll see “Smush in Bulk”. Click on the “Bulk Smush 50 attachments” button and wait. You’ll need to click again on the button every 50 images if you’re using the free version of the plugin. Once every image on your site has been optimized by WP Smush, you can rest assured that you have saved a lot of loading time. Check the difference on Google PageSpeed Insights!

Minimizing HTTP requests

The next problem I was facing was the fact that my site was requesting way to much files. When using WordPress, the most convenient way to enhance your blog functionality is to add plugins. Plugins are cool, but many of them have to do extra HTTP requests (mostly css and js files) in order to work properly.

How I fixed the problem: I used the best ever caching/minify WordPress plugin, the mighty W3 Total Cache. The plugin offers a lot of possibilities in order to cache your website and make it faster. For instance, a super useful thing in your quest for speed is the Minify options: You can easily merge 3 css files in one, which will ultimately result in a single HTTP request instead of three. I turned on all caching options (besides those requiring paid third parties services) and minified my JavaScript, CSS and HTML.

The Monarch plugin I’m using was adding The Open Sans font to my blog, which caused an unnecessary HTTP request. To remove the font and the consequent warning issued by PageSpeed Insights, I added the following to my WordPress theme functions.php file. This little chunk of code simply removes the font added by the plugin.

//Remove Open Sans font added by Monarch
wp_dequeue_style( 'et-open-sans-700' );

Also, the little form provided by MailChimp for my mailing list was importing a small css file. I just removed the call to that stylesheet and pasted the css rules in my main .css file.

Another important thing, I removed the Facebook “Likebox” widget which was loading a ton of stuff such as css and JavaScript files. I plan of using a simple icon on my site header instead of that bloated widget.

Additional fixes

As all websites are different, here’s a list of additional tips that might be useful to help you fix the problems you’re facing.

The first one is to use a quality host. If your website is hosted on a crappy, cheap shared hosting, don’t expect it to be fast. My web host, Vidahost is fast and Google PageSpeed Insight said the server is very responsive. So a thumbs up for them! If you’d like to join Vidahost, you can use the coupon code CATSWHOCODE to get 10% off your hosting.

There’s a somewhat little-known, but very efficient WordPress plugin that you might want to try: Speed Booster Pack. It is specially designed in order to make your site faster and rank higher on major speed testing tools. It has a few very interesting options that you should check and experiment with.

Clean code! It might seem obvious, but yet a ton of sites are using poorly optimized code, whether php or html/css. A clean and optimized code loads faster than a bad one. So if you’re looking for speed, make sure that your code is properly optimized.

Use a CDN: A CDN (Content delivery network) is a network of servers which are spread throughout the world. Each of those servers keep a copy of your static content. With a CDN, when a user visits your site he is being redirected to the closest server to their location.

Can’t fix your site? Get help from someone with experience. Fixing speed of a website isn’t easy and there’s little 100% out of the box solutions, as all websites are different. Getting help from a speed expert could be the best way to speed up your site. Want me to help? I can do so at a reasonable rate, feel free to contact me.

And now, let’s have a look at how Cats Who Code is fast, according to Google PageSpeed Insights: