Google+ Comments for WordPress Plugin

google-plus-commentsFor many years now Facebook has had a very popular login feature and also offered the ability to easily integrate blog comments using your Facebook account. These options have proven to be very popular with all types of webmasters as they provide several convenient features and also help to discourage spammy or anonymous comments.

It always surprised me that Google wasn’t in this game, but the introduction of Google+ seems to offer Google the ability to offer these features to webmasters and be the ones collecting this information.  According to reports, apps that support Google’s login are now getting favorable search treatment and Google is starting to really push this feature.  Then last month, Google announced that Google+ comment integration is now available for Blogger users. So, what about WordPress users?

Not long after the Blogger integration was announced, the necessary code was discovered to do this manually using the following code:


<script src="">

Valid HTML5 version:

<script src="">

Comments counter HTML (replaces < g:comments >):

<g:commentcount href="[URL]"></g:commentcount>

Valid HTML5 version (replaces < div >):

<div data-href="[URL]"></div>

Replace ‘[URL]’ with the URL of your web page and fit the ‘width’.

Link your web page to your Google+ profile to verify authorship.

Dynamic Google+ Comments HTML:

<div id="comments"></div>
gapi.comments.render('comments', {
    href: window.location,
    width: '624',
    first_party_property: 'BLOGGER',
    view_type: 'FILTERED_POSTMOD'

Google+ Comments Counter:

<div id="commentscounter"></div>
gapi.commentcount.render('commentscounter', {
    href: window.location

Google+ Comments for WordPress Plugin

Fortunately, the WordPress community has already come through with an easier solution, the Google+ Comments for WordPress plugin. This plugin makes the comment section tabbed by seamlessly adding tabs for Google+ Comments, Facebook, Disqus, WordPress Comments, and Trackbacks. Early reviews are promising and I manage this plugin will continue to evolve over time.

If you decide to give this plugin on your website leave us a comment and let us know how the setup went.

  • Leave a Comment
  • PSA: Massive Botnet Attacks on WordPress Installations

    Over the past 24 hours it has come to our attention that a large network of over 90,000 IP addresses have ramped up their use of a brute force attack to target WordPress blog installations. According to several published reports, the botnet is attempting to gain access to WordPress installations by using the default Admin user name and trying multiple passwords. By default, WordPress allows unlimited login attempts either through the login page or by sending special cookies. This allows passwords (or hashes) to be brute-force cracked with relative ease.

    Popular hosting providers CloudFlare and HostGator are reporting that the scale of the current attack is much larger than what they typically experience, with some reports claiming that they are blocking 60 million requests per hour during peak times. After reviewing our logs we’ve already noticed several failed login attempts using the username Admin.

    What can I do to protect my WordPress installation(s)?

    1. If your username is currently set as Admin, change it to something custom. The easiest way is probably by using something like the Better WP Security WordPress plugin.
    2. Change/strengthen your password. Your password should include capital letters and symbols (%+!#)
    3. Install a plugin to limit login requests.  We use the appropriately titled Limit Login Attempts WordPress plugin, but there are several other plugins with similar functionality.

    Once that is done, sit back and hope for the best!

    Update: HostGator has provided additional tips.

  • Leave a Comment
  • How to Handle a Hacked WordPress Install

    WordPress is the most popular Content Management System in the world, and a significant percentage of the sites on the Internet use it. That popularity is well-deserved, but it also makes WordPress an irresistible target for hackers who want to spread malware.

    How to Tell if Your Site’s been Hacked

    Sometimes it is obvious that your site has been hacked. Occasionally hackers will simply redirect the site to a different server, so that visitors to your domain end up at a site infected by malware, a site displaying advertising the hacker can profit from, or a porn site. But often hackers add malware or spam links to a site which they want to remain undetected for as long as possible. Having a hacked site can infect your visitors with malware, and it will almost certainly result in a huge hit to your SERP rankings, or even blocking by search engines, so it’s important to be vigilant. There are a number of tools available to webmasters to determine whether a site is vulnerable and whether it has been hacked.

    WP  Security Scan

    The WP Security Scan extension won’t tell you whether your site has been hacked, but it will check for possible attack vectors and vulnerabilities, and offer suggestions for fixes. Of course, often the vulnerabilities will not be in WordPress itself, but in some other part of the software stack. The best way to ensure that there are no known exploits that hackers can use is to keep your software as up-to-date as possible.

    Google’s Safe Browsing Diagnostic

    Google has a service that enables webmasters to see whether they consider a site to be dangerous to visit. Copy the following URL into your browser address bar and replace the part following ‘?site=’ with your site’s URL.


    Sucuri offers a free site scanning service that will catch major problems, and a paid for monitoring and cleanup service that can help if you are hacked.

    Using these tools together can help you ensure that your site remains safe.

    What Should You do If You’ve Been Hacked

    Unless you are an experienced and expert developer or website administrator, cleaning a site with any level of confidence by yourself is almost impossible. Even if you think you have found all the malicious files and removed all the spam links, the files that make up WordPress itself may have been altered so that they reinfect a site after an attempted cleanup.

    Contact your hosting provider and let them know you’ve been hacked. You might not be the only victim and the host provider’s sysadmins may already be taking action.

    Securi, as mentioned above is an excellent tool, and it will attempt to auto-clean your WordPress installation. Should you choose not to use Securi, or hire a professional to clean your site, then the next best option is to delete the site and restore it from backups.

    Hopefully, your site is hosted with a provider that offers a comprehensive backup service, in which case restoring the site to a previous version should be very simple. If not, we are going to assume that you have been making regular backups of your WordPress database.

    Download a fresh install file from, to replace any files that may have been altered during the attack. Do not use the same passwords on the new install as you used on the hacked site.

    After you have installed a fresh version of WordPress you can restore the WordPress database from a backup that you know to be clean.

    Since you know that your site has been hacked once, and that there were vulnerabilities that malicious parties were able to exploit, if possible, it may be best to completely reinstall the server and restore from backups. At the least very scan the server with an anti-malware tool. If you are reasonably sure that the infection was limited to WordPress, then you should update all of your software to the most recent versions, to close vulnerabilities. If you’re using shared hosting your provider should take care of this for you.

    If you haven’t been taking database backups, it may be possible that the WordPress database has not been breached, and that a fresh install of WordPress using the existing database is enough, but in that case be extra vigilant of alterations, follow the rest of the above advice, and start taking regular backups!

  • Leave a Comment
  • How to Protect WordPress from Malware Infections

    WordPress is installed on so many websites now, the global reach is comparable to a company like Microsoft. Hackers, scammers, and phisherman target Windows because it’s installed on millions of computers all over the world. If you’re going to break into computers with malicious intent, you want the biggest target.

    You will find (at times) some proponents of other popular open source CMS software (Joomla, Drupal) may try to say “WordPress isn’t safe, look at all the hacked websites”. WordPress is actually very stable, mature, and secure. But by it’s very nature, being software, it must be maintained (or security holes appear over time). If everyone kept WordPress, plugins, and themes updated, and performed just the slightest bit of preventative maintenance and hardening, the amount of compromised WP websites would probably go down by 90%. In this article we’re going to go over the basic steps of how to protect your WordPress website from malware, virus infections, and malicious code and scripts.

    First let’s talk about some basics you should know…

    What is (website) malware?

    You probably already know the word “malware” from PC’s and computers. Computer viruses have been around a long time, as well as virus scanning software. With the Internet age came “spyware” (programs that spy on what you do and send the details to a remove computer), as well as “anti-spyware” computer software. You might also have hard about trojans, and key-logging software as types of computer virii. The term “malware” in conjunction with a computer means something installed on your PC in order to deliver a payload. Like installing a browser toolbar, and having it (on the backend) install a script, program, or trojan without your knowledge as the payload.

    Google started tracking malware in websites a few years back as part of Google webmaster tools. Malware (at that time) was known mostly as something installed in your website designed to deliver a payload unknowingly to the website visitor (also like a virus, trojan, program, script, etc.). Now, the term is used to cover nearly any compromised website wither it delivers an actual payload, redirects the user to a rogue website, or just plain contains simple SEO spam.

    How do websites get infected with malware?

    If you think about the amount of WordPress websites online (more than 73 million and counting), when reports come out that say “10,000 websites hacked from ABC vulnerability” it’s a small percentage in comparison to the whole. Then again, that’s 10,000 broken websites that are either down, redirected, or infested with spam.

    Often people have a perception that there are actual people (or hackers) trying to break into websites. That’s not really the case, it’s an automated process. Hackers, spammers, and criminals write scripts to seek out and search for websites with specific vulnerabilities they can use to break in. They watch the latest security holes patched in WordPress itself, as well as themes and plugins. They also look for other software with holes, such as Joomla, Mambo, Drupal, phpBulletin, Simple Machines forum, phpBB, and anything else they can find. Often scripts are written to break in through one hole, and then just infect all PHP files, all sites in a hosting account, or just all WordPress installations at once.

    So think about the home you live in and it’s security. You have locks on the doors and windows, and if someone were trying to get in – you’d know about it right away. The bulk of websites online are in shared hosting accounts. Unless you have some alerting or monitoring installed for your website (and even if you do), the only place break-in and hack attempts are stored is the server logs. You don’t know it but your website is being “attacked” night and day 24/7 hundreds (if not thousands) of times. You have no idea that something is constantly trying to break into your website. If you did – you’d actually beef up the security a bit.

    Back to how the websites get infected. These automated scripts look for security holes in WordPress itself, themes, and plugins. If your website (or themes or plugins) are out of date – you might be open to one of these attacks looking for a way in. But this isn’t the only way.

    Another way websites can be compromised (any website, not just WordPress) is by using an insecure connection to either login to FTP, your wp-admin dashboard, or your web hosting account. Remember when we talked about computer viruses and malware? If your PC is compromised and you connect to your WordPress website, your connection information could be sent to a remove PC by a keylogger or trojan. Even is your PC is clean, if you connect to any of these by an insecure connection such as Starbucks connection, public wifi in a hotel or airport, the same thing could happen (same if your home wireless router isn’t secured).

    Yet another way your WP website can be infected is through your webhost itself. Maybe your account is managed with cpanel or Plesk control panel and your webhost hasn’t applied the latest patches for that software. Hackers can get in through those security holes. What if an exiting employee from a webhost steals the password files (which has actually happened) – you could be compromised. What if someone external breaks into your webhost and steals your login information (which has also happened at multiple webhosts multiple times), you can also be broken into.

    More often than not what we do see, are large webhosts with shared webservers where hackers break into as many sites as they can on one box at once (bad neighborhood or guilt by association break-ins). Hosts that do stupid things like leave directory indexing on by default – don’t help matters much.

    How to Protect WordPress from malware?

    Now that you know what malware is, and how websites get infected, it’s time to find out how to protect your own website from malware (infections). While we can’t give you complete step by step instructions, we can give you some great points to follow which will make your website more secure and hardened than it ever has been.

    • Reset your password(s): regularly reset your WordPress admin, FTP, and web hosting control panel passwords every 30-60 days. Be sure to use a 12+ character strong password from somewhere like Never use the same password at multiple websites or for multiple accounts.
    • Update everything: as previously mentioned, be sure to keep WordPress itself updated, and all plugins and your theme as well at all times. Check to see if your theme has an update available if you purchased it from a developer or a theme house. Have it reviewed by a competent WordPress developer once per year for vulnerabilities if it was custom coded.
    • Remove unused and outdated items: The worst security holes are the ones that you forget about. Always remove all themes and plugins that are unused and inactive. In addition be sure to remove (or at least have an expert check out) any plugins that haven’t had an update in 12-18+ months or more.
    • Get rid of common WordPress elements: Your WordPress installation shows what version you are running in the meta generator tag of every HTML page it displays sitewide. Use a security plugin like Secure WordPress or Better WP Security to suppress this from being displayed in your public pages. You can also remove, hide, or limit access files like readme.txt which also display WP version information.
    • Limit Access: Limit and give admin access to only those with a “need to know” basis within your WordPress website. You should be able to count full site admins on one hand (preferable one or two fingers). Give the rest lesser user roles as needed.
    • Setup alerting and monitoring: There are all kinds of free services (some by web hosting companies) that will alert or monitor you if your website is down (or if certain pages have changed in content)
    • Register with Google Webmaster Tools: If you register with Google Webmaster Tools and they find malware in your website, they will notify you via email. Keep in mind (in our experience) by the time they notify you, your website could have been infected for days or weeks (or longer)
    • Monitor changed files: There are many free plugins that will monitor your website for changed files, Better WP Security is one of them.
    • Update wp-config security salts: Since before version 3.0 the wp-config.php file of every WP installation has contained “security salts” and a URL to get random ones to update the file with. Be sure to update your wp-config file.
    • Install and configure a security plugin: Setup and configure an all-inclusive security plugin, something like Better WP Security or Secure WordPress
    • Setup and test a backup solution: By all means, make sure that in the event something does happen you have a disaster recovery plan. You can use a free plugin, premium solution, or web based service to backup your website to an offsite location for recovery in case you are hacked, or something at your web host goes down. This is even protection against issues if you upgrade WordPress or plugins and a conflict takes your website down. At least with an option like this, if you are taking regular versioned backups, you can easily revert to the last known good version

    With just these few bullet points, your website security can be improved by nearly 95% (or more).

  • Leave a Comment
  • CRON Jobs Give WordPress Users Peace of Mind

    If you’ve never had a website go missing, then you’re very lucky. Your host can have a network error or hardware failure that loses your site’s files. A malicious hacker can penetrate your FTP server and replace your site with files of his choice. You might get curious about a new plugin, install it, and break your site to pieces in the process. No words really describe the panic you feel when you realize your website is gone!

    If your host allows you to use CRON jobs, you can protect yourself from all those things by running a daily backup of your database and web site files. If you lose your site for any reason, you can put it right back in a few minutes.

    A CRON job is script that your web server executes at a specified time. CRON comes from the word chronograph, and it is a time-based job scheduler for LINUX based operating systems. Most WordPress sites are running on such an operating system. If you have access to a CRON scheduler through your hosting control panel or have command-line access to your hosting server, you should be able to write a shell script to back up your database and site files.

    The first thing you will need is a shell script. The script will connect to your database, export the whole thing to a file, and zip the file up so you can store it safely somewhere. Then, it will zip up all your website files.

    If you have a host panel where you can create and edit a file, you can do this there. Otherwise, open any non WYSIWYG text editor and create a file called The .sh file extension indicates this is a shell script file.

    export TERM
    NOWDATE=`date +%a` # Sets the date variable format for zipped file: Sun
    clear # clears terminal window
    echo "Hi, $USER!"
    mysqldump --opt -Q -h your-website-host-name --user=your-db-user-name --password=your-db-password your-database-name | gzip -v9 - > /www/public_html/backups/MySQL-$NOWDATE-yourwebsite.sql.gz

    The first line is an indicator to the server for which shell processing language to use. Your server might require

    #!/bin/bash or something else there. Use echo $SHELL from the command prompt to determine your shell type if you have command line access.

    The TERM instruction tells the server what terminal type it is communicating with; in this case, a text terminal.

    Next we create a variable named NOWDATE and use a little script magic to set it to be equal to the abbreviation for the current day of the week e.g. Sun, Mon, Tue, etc.

    The mysqldump command will “dump” the entire database including create procedures and insert procedures for all the current data.

    Replace your-website-host-name with your website host name for your database. You can find this in your wp-config file if you don’t know it.

    Replace your-db-user-name, your-db-password, your-db-name with actual values. Again, these values are likely exactly what they are in your wp-config file.

    Replace /www/public_html/ with whatever your hosting account’s root path is.

    Replace yourwebsite with some meaningful name.

    Now, save the file. You need to set the permissions on the file so that it is executable. If your cpanel has a cron scheduler, just add this file to the list of files it runs. If you need to edit your crontab from command line, see this tutorial.

    To back up your site files, as well as your database, add a few more lines to your script.

    echo "Zipping wordpress directory structure..."
    tar -czf $HOME/backups/$NOWDATE.mywebsite.tar.gz $HOME/public_html/*

    Hopefully, you do have a directory outside your public web root so that your backup files are stored in a location that is not accessible via the internet.

    The tar command will pack the files up into a tarball for you (like a zip archive).

  • Leave a Comment
  • How To: Add a Twitter Link to Your WordPress Blog

    Twitter is all the rage these days and it doesn’t seem like it will be going anywhere any time soon.  With that said, it often surprises me that many WordPress blog owners  don’t offer a convenient way for their readers to retweet their content.  Anyone can grab a Twitter WordPress plugin to tweet their new content as it is published, but what about your older content?

    Rather than passing up all that potential traffic, I’ve found that offering a link somewhere within your post (optimally at the bottom of each post) is a great way to help your readers and incoming search engine traffic to promote your content for you.  When people find great content they like to share it with others, so why not make it easy for them?

    Not only is adding a “Tweet This!” link a great choice, but it is really easy to do.  Chances are if you do a search on Google for code to use you’ll find something like the following:

    <a href=" reading <?php the_permalink(); ?>" title="Click to send this page to Twitter!" target="_blank">Tweet This!</a>

    This code works just fine, but is not the most optimal solution in my opinion.  Depending on the permalink structure your WordPress blog uses, combined with the length of your domain name, it may be difficult to fit the link into a 140 character tweet.  It also doesn’t leave room for the person to add their own comments to the tweet.

    As a proposed solution, I recommend using some WordPress code like the following:

    <a href=" @HackWordPress <?php the_title ();?> <?php echo get_settings('home'); ?>/?p=<?php the_ID(); ?>">Tweet This</a>

    This code will automatically insert the “RT” and your Twitter account name (the above example uses our Twitter account, @HackWordPress) then use the ID form of your post with the tweet.  When people click the link in the tweet, they will then be redirected to the actual post using your blog’s selected permalink structure, making a convenient and typically short URL.

    Have you integrated Twitter into your WordPress blog? Share your strategies in the comments!

  • Leave a Comment
  • Separating Trackbacks from Comments in WordPress 2.7+

    Back when WordPress 2.7 was released, the WordPress team introduced a completely revamped comment form that included integration of threaded comments into the core software, introducing some dramatic changes with how comments are handled.   Unfortunately, this change broke one of the most popular comment hacks, separating trackbacks from comments.

    Since then, several people have stepped up and shared some great hacks for separating trackbacks from comment in WordPress 2.7 or newer blogs .  So far the best guide I’ve found came from, which can be viewed here.  Click over and follow those steps get everything separated.

    Note: The above guide is only for people using WordPress 2.7 or newer installations.  For people using WordPress 2.6 or earlier, you’ll want to use this tutorial.

    Once you’ve got the comments successfully separated from the trackbacks, there are a couple additional tweaks you may want to do to clean up how things look (it really depends on preference I suppose).   The first is to clean up your trackbacks/pingbacks by only displaying the title instead of an excerpt and everything else.   In order to do this, you’ll need to find the following code in your comments.php file:

    <?php wp_list_comments('type=pings'); ?>

    Now replace that code with the following:

    <?php wp_list_comments('type=pings&callback=list_pings'); ?>

    Lastly, you’ll need to add the following code to your functions.php file (which can be created if you don’t already have one):

    function list_pings($comment, $args, $depth) {
    $GLOBALS['comment'] = $comment;
    <li id="comment-<?php comment_ID(); ?>"><?php comment_author_link(); ?>
    <?php } ?>

    That should clean up the trackbacks/pingbacks section and you can also apply the same changes if you use a plugin to display tweetbacks.

    The other thing you may want to do is fix the comment count to only show actual comments, filtering out the trackbacks/pingbacks which are included in your comment count by default.   Simply add the following code to your functions.php file (which again can be created if you don’t already have one):

    add_filter('get_comments_number', 'comment_count', 0);
    function comment_count( $count ) {
    if ( ! is_admin() ) {
    global $id;
    $comments_by_type = &separate_comments(get_comments('status=approve&post_id=' . $id));
    return count($comments_by_type['comment']);
    } else {
    return $count;

    So there you go.  Anyone have any other tips for cleaning up your comment form?

  • Leave a Comment
  • How to: Use Thumbnails Generated by WordPress

    One of ten brilliant tips that I shared yesterday, display images on your blog’s homepage without any custom fields or any additional functions.php script, something I first saw on WebDeveloperPlus.

    How do you do it? First log in, on the sidebar select ‘Media’ (which is under ‘Settings’). You’ll then be taken to a page with an option to change the thumbnail size of images. Change that to whatever size you want your images to appear as. Next, insert the code below onto your homepage, archive page, whatever.

    //Get images attached to the post
    $args = array(
    'post_type' => 'attachment',
    'post_mime_type' => 'image',
    'numberposts' => -1,
    'order' => 'ASC',
    'post_status' => null,
    'post_parent' => $post->ID
    $attachments = get_posts($args);
    if ($attachments) {
    foreach ($attachments as $attachment) {
    $img = wp_get_attachment_thumb_url( $attachment->ID );
    break; }
    //Display image
    } ?>

    Then, to display your image you can just echo out the $img tag we just created:

    <img src="<?php echo $img; ?>" alt=" " />

  • Leave a Comment
  • How To: Hack WordPress Theme Template Pages

    The key to being able to display exactly what you want in WordPress is understanding WordPress theme template pages. These are the theme files that display pages, not the ones that perform functions like comments, sidebar, etc. Most of us don’t use the WordPress default theme that comes with installation, and end up downloading a free theme from the Internet. This is a great way to customize your blog, but not all theme authors code their theme the same way. The capabilities of that theme largely depend on how much time the web designer took to code it, in addition to their knowledge of WordPress itself.

    I’m going to explain everything you need to know to be able to customize all your theme pages any way you want, and this will give you enough information to begin coding your own theme as well. Even if you’re an ‘expert’ theme coder, you should learn something new from this article.

    How WordPress Works

    The most important thing you could learn about WordPress is the Template Hierarchy, or – “the order in which WordPress calls pages”. The ONLY file that is required in the PHP files of any WordPress theme is the “index.php”. That’s it! That one file could handle every single function WordPress performs (if you wanted it to). Or, you could have a WordPress theme that had a PHP theme for for every single WP function (or anything in between).

    The Order of Things

    Every time a WordPress page is called the WP ‘engine’, if you will, determines (through process of elimination) what kind of page it is. It’s kind of like a “where am I?” function. WordPress says “what page am I…” and in turn tries to call pages in a specific order. If WP doesn’t find the PHP file it needs it just defaults to the “index.php” file and uses it instead. There are 9 basic kinds of pages WordPress looks for first:

    Am I the Home Page?
    If WP thinks it’s on the home page it will look for “home.php” first, and “index.php” second.

    Am I Post Page?
    (Single) post pages look for “single.php” first, and then default to “index.php”.

    Am I a ‘Paged’ Page?
    (Static) or ‘paged’ pages in WordPress look for a “pagetemplate.php” first (if assigned when published), “page.php” second, and default to “index.php” last.

    Am I a Category Page?
    When WordPress determines it’s on a category page first it looks like a category specific ID page, such as “category-7.php”. If it doesn’t find that it next looks for a “category.php” (which would be used on every category page). If that’s not there is searches for “archive.php”, and last it defaults to “index.php”.

    Am I a Tag Page?
    If WordPress is on a tag page it tries to load “tag-slug.php” first, with ‘slug’ being the name of your tag. If your tag is ‘wordpress hacks’ the tag slug page would be “tag-wordpress-hacks.php”. It that’s not available, WP next looks for “tag.php” which would load for all tag pages, then “archive.php”, and if that’s not there last it defaults to “index.php”.

    Am I an Author Page?
    If your blog has multiple authors, first it looks for “author.php” to display the details. If that’s not there, it tries to load “archive.php”, and last it defaults to “index.php”.

    Am I an Archive Page?
    Archive pages are loaded when WordPress loads a date based page for previous posts. First it tries to load “date.php”, then “archive.php”, and last it defaults to “index.php”.

    Am I a Search or 404 Page?
    If WP determines it’s on a search (results) or 404 (not found) page the it tries to load either search.php or 404.php. If not, the default is once again “index.php”.

    Am I an Attachment?
    Out of all the WordPress theme template pages, the attachment page is probably the one used least, and I have to admit – I’ve not seen a single one of these in any of the hundreds of themes I’ve downloaded. WordPress uses these special pages usually for uploaded content, which would explain why it first looks for “image.php”, “audio.php”, “video.php”, or “application.php”. Then it tries to find “attachment.php” or “single.php”, and if none of those are available it also defaults to “index.php”.

    Inner Workings of WP Theme Templates

    As I said before, you could use a single index.php file to handle the 9 types of pages. You would simply code in some conditional tags, like I showed you in the last tutorial I wrote here on WP Hacks. A single index.php would then just contain code to say if is_home, do this, if is_single do that, etc. That’s a lot of code for just one page, and a bit unorganized – and it doesn’t leave a lot of room for customization.

    Coincidentally, like WordPress searches for 9 basic pages – each theme template page also contains 9 basic WordPress elements:

    1. a header call
    2. opening of ‘the loop’
    3. a call to get the permalink and (some) meta
    4. a call telling WordPress what to get
    5. a call to get either the content or an excerpt
    6. (maybe) more meta
    7. closing of ‘the loop’
    8. a sidebar call
    9. a footer call

    Those are only the WordPress elements, of course the PHP code to make them work is usually scattered throughout the appropriate HTML code make your theme’s layout and graphic design work properly. I’m going to explain these elements a bit more so you can understand how you can customize (or create) nearly any theme template page.

    Header, Sidebar, and Footer calls

    I’m going to handle all 3 of these elements at once, since they are all basically the same. When you see this code in a template:

    <?php get_header(); ?>

    WordPress is simply opening the “header.php” file. The same is true for get_sidebar (sidebar.php) and get_footer (footer.php). You could have multiple headers, footers, or sidebars, see the earlier link above for conditional tags.

    Opening of “the loop”

    The infamous “WordPress Loop” is when a call goes out to the database to do something until WordPress says “stop”, i.e. ‘get me the most recent full text posts in their entirety’. The structure of ‘the loop’ changes depending on what kind of page your displaying, and each of the 9 basic types of pages WordPress tries to load has a ‘loop’.

    The opening of the loop generally looks like this:

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

    You may see it broken down with have_posts on one line to define conditional tags with the while and the_post on another, but it’s still the opening of the loop, and it’s pretty much the same in all pages. One way to use the multi-line loop opending is to place a parameter between “if have_posts” and the rest by using query_posts in between to show only a single post, posts from a time period, the last post only, posts from certain categories, or even change the ordering of posts being iterated in the loop.

    A Call to Get the Permalink and (some) meta
    The very last section of the loop opening (the_post) actually makes individual data available through each iteration of the loop. This data referred to usually as “post meta” because it’s descriptors and identifiers for the individual content being looped through. Typically things like the permalink (URL), title, date, etc. I say ‘some’ meta, because most themes show some things before the individual post content, and then some after – such as categories and tags.

    Here’s a short list of things you can call in post meta: the_permalink, the_ID, the_title, the_time, the_author, the_author_email, the_author_posts_link, the_category, single_cat_title, the_tags, single_tag_titls, edit_post_link, comments_popup_link, comments_rss_link

    Example code you might see for post meta would be something like this:

    <div class="post" id="post-<?php the_ID(); ?>">
    <h2><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h2>

    A Call Telling WP What to Get
    Next WordPress will decide how much of the actual individual post content to get for you. How much is gathered from the database depends on whether your look uses “the_content” (to get it all) or “the_excerpt” (to get part of it).

    (Maybe) more meta
    As I previously mentioned, the common things to see after a post are assigned categories or tags, and sometimes you see an “edit” link here as well. Some themes even put date published meta after the post content.

    Closing of ‘the loop’

    The code looks like this:

    <?php else : ?>
    <?php endif; ?>

    Typically it’s on more than one line in case you want to build an option in, such as a message “Sorry, we didn’t find anything”. After the sidebar, before the sidebar and footer calls, is where you typically find the “next” and “previous” navigation links.

    Bastardized Loops?

    Well, just because most loops look like the examples I just gave you, doesn’t mean you can’t bastardize them in just about any way you can imagine. I recommend you read the WP Codex page The Loop in Action for examples of archive, category, and single post formats – as well as static home page.

    The Codex official page for the loop has several examples of how to place multiple loops in one page.


    Armed with just a tiny bit of knowledge, you can hack just about any WordPress theme template page to do just about whatever you want! Now that you understand (in great detail) how WordPress calls it’s pages and how the loop works, you can conquer any task! Have fun customizing your blog’s theme!

  • Leave a Comment
  • How To: Use WordPress Conditional Tags to Hack Your Theme

    By using simple conditional tags – it’s pretty easy to add some very basic hacks to your WordPress theme to have more control over what’s displayed when.

    Here are some things you could do with a conditional tags:

    • Display something only on certain pages
    • Display something only on certain categories
    • Display something in header and footer only at certain times
    • Display something only on sub-children of particular pages
    • Display something only in the WP dashboard
    • Display something in the sidebar only when certain conditions are met
    • Do something only when there’s a “sticky” post
    • Do something only when a “page template” is used
    • Do something only for “author pages”
    • Display something only on search or 404 pages

    Let’s say you want something to display only on the homepage, or just category pages, or maybe just your 404 (not found) page – it’s quite easy to do. You don’t have to be a hardcore programmer (I’m not for sure) to implement these very simple theme hacks.

    Where to Use Conditional Tags

    It all depends on your your theme is structured. I’ve seen WordPress themes that a single “index.php” file handle just about everything, and other ones that use only the home.php, index.php, single.php, archive.php, and category.php files. You could handle everything with a bunch of code in one file if you want using conditional tags, have individual files for each thing, or any combination in between.

    Most themes I’ve encountered usually have an index.php and a single.php only. If you want to know what pages WordPress looks for first in a theme before defaulting to the “index.php”, read the official WordPress Template Hierarchy page.

    Conditional tags are great because you can use them both in and out of the loop. You can use them directly in theme pages, but you could also use them in your header, footer, comments, and sidebar files. Actually the sky is the limit, and you have only your own imagination to limit you!

    Conditional Tag Examples

    The worst thing I see on most posts about conditional tags is that they don’t have a lot of examples for you to draw from – so I’ll try to give you a few ideas to get you started…

    If This is XYZ page

    One of the most common ways to use a conditional tag is to add a filter of sorts to tell WordPress “if I’m on ‘XYZ’ WP page – then do this. The most common reason would be maybe to show certain things (ads, text, messages, graphics, scripts, flash) in certain places.

    For example, let’s say you want to display a message to visitors on your home page only…

    <?php if (is_home()) { ?>

    Welcome, you will only see this message on my homepage!

    <?php } ?>

    replace “is_home” with “is_front_page”, “is_single”, “is_sticky”, “is_page”, “is_page_template”, “is_category”, “is_tag”, “is_author”, “is_date”, “is_archive”, or “is_attachment” to make your message show up on nearly any WordPress page. Remember, once the condition is met, you can “do” anything – from including a file to showing special graphics, running a script, anything! You could use this condition for example to show an ad on just your homepage, or just single pages.

    If this is XYZ page show this, else show that

    The nice thing about conditional tags is the fact that you can have as many conditions as you want…like this:

    <?php if (is_home()) { ?>

    <p>Show this!</p>

    <?php } elseif (is_single()) { ?>

    <p>Show this instead!</p>

    <?php } elseif (is_category()) { ?>

    <p>Show something different!</p>

    <?php else { ?>

    <p>Show this if no conditions are met</p>

    <?php } ?>

    OR – you could even structure it in such a way that you lump some conditions together like this:

    <?php if (is home() || is_single() || is_category() || is_page()
    || is_archive() { ?>

    <p>Show this on all those pages!</p>

    <?php } ?>

    The double-pipe or || in the code signifies “OR”, so WordPress knows, if this is home, or a single page, or a category page, or a “page” page, or an archive page – then so something.

    Show Everywhere, Except…

    Sometimes you want to show something everywhere possible except just one or two places…

    <?php if (is_home()) {
    else { ?>

    <p>Show this everywhere!</p>

    <?php } ?>

    With this code we just say if it’s “home” do nothing, else show do this. You could add multiple conditions (exclusions) to this using the || OR operator as in previous examples.

    Getting even more specific

    One thing I hadn’t mentioned was that you could pass additional parameters to the conditional tags for even finer grained control. For example, instead of targeting are single post pages with “is_single”, you could actually target just one using any of these formats:

    is_single(’25’) // uses posts ID
    is_single(‘Title of my post’) //uses the exact title of the post
    is_single(‘title-of-my-post’) //uses the permalink of the post
    is_single(array(25,’this title’,’this permalink’)) //uses when any of the 3 are true

    You can use similar parameters for paged pages, template pages, categories, tags, etc. The official WordPress Conditional Tag page in the Codex lists them all.

    Force WordPress Functions for Certain Conditions

    Have you ever not wanted to add people to your blogroll because their link will display on EVERY SINGLE page of your WP powered site? That’s an easy hack with conditional tags, because you could hack your sidebar to display your blogroll ONLY on your homepage like this:

    <? php if (is_home()) {

    You could modify this to display just about anything in the sidebar for whatever conditions you want. Let’s take this a bit further though – let’s say that maybe I want a special header or footer when certain conditions are met? You can do that too…

    <? php if (is_home() || is_single() || is_page()) {
    elseif (is_category() || is_tag()) {
    include (TEMPLATEPATH . '/header2.php');
    elseif (is_404() || is_search())
    include (TEMPLATEPATH . '/header3.php');
    } ?>

    Using that example code you could have as many different headers, footers, or sidebars as you wanted and you could include them for whatever conditions you specified. Just replace get_header with get_footer or get_sidebar, and edit the rest include the files you want.

    Using Conditional Tags to Change Styles

    So far my conditional tag examples have been to show you how code conditions to do this or include that. Another very simple (and powerful) was to use conditional tags is to just use them for coding style. You could have any element (paragraph, div, heading) change colors or font size or anything related to style when certain conditions are met.

    Let’s take a very simple example, maybe your pages have content contained within one div like this:

    <div id="content" class="main">
    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php endwhile; ?>

    In most themes, that main “div” is styled the same way on EVERY single page of the theme. Maybe you want it styled one way for your homepage, but another for paged pages, single posts, archives, etc. What you do in this case is to write different classes in your stylesheet for each and call them something like “single”, “archive”, and “paged” – and then you code it like this:

    <div id="content" <?php if (is_home()) { ?> class="home"
    <?php } elseif (is_page()) { ?> class="paged"
    <?php } elseif (is_single()) ?> class="single"
    <?php } elsif (is_archive()) { ?> class="archive" <?php } ?> >
    <?php if (have_posts()) : ?>
    <?php while (have_posts()) : the_post(); ?>
    <?php endwhile; ?>

    You use any variation of this to control any element of your theme at will under nearly any condition. This would also be a great way to control your Post title and meta and have it display different things on different parts of your WordPress powered site.


    I think mostly that the power of conditional tags is widely underutilized. Many of us just take for granted the way a theme works and looks, and forget that with just a few strokes of code and some imagination – we can change just about anything under the sun in our WordPress theme! I’d like to see some comments on what kinds of things you’ve used conditional tags for in your WordPress site (code samples welcomed!).

  • Leave a Comment