Disclaimer: You should think twice about interacting with the Slack API using client facing JavaScript like jQuery on a public website because your webhook (the special URL that Slack generates for you) will be public. This means that anyone could post anything in your Slack channel without being authenticated.

It is possible to interact with the Slack API securely using Node.js but the following tutorial is just provided for demonstrative purposes.


Slack is pretty great for teams, I use it all the time for work and just for groups of friends. At one point I was asked to provide a proof of concept for posting a message in Slack when a form was submitted through Contact Form 7 on a WordPress site.

In order to prototype this quickly without spending time to create a plugin and do it the ‘right’ way by using cURL with PHP, I decided to go the JavaScript route for a quick and dirty example.

This example assumes you have Contact Form 7 installed on your WordPress site.

Posting to Slack with Contact Form 7

The actual code that we need to use is going to look pretty messy because we need to minify it to make it work with Contact Form 7, so I’m going to explain it first.

var name = jQuery('.slack-name').val();
var email = jQuery('.slack-email').val();
var occ = jQuery('.slack-occupation').val();

var requestBody = "A request was made to join the Slack channel by: Name: " + name + ", Email: " + email + ", Occupation: " + occ + ".";

	'{{ WEBHOOK URL }}',
	'payload={"channel ": "#{{ CHANNEL TO POST TO }}","text ": "' + requestBody + '" }'

We start out by defining our variables and what we want to send to Slack. Because of the way Contact Form 7 creates it’s forms, we can’t just use the handy $.serialize() method that jQuery provides. Instead we need to manually grab the values.

Then in requestBody we form our text message that we want to send to Slack.

Finally using $.post() (a facade of $.ajax()) we make our request using the webhook URL that Slack gave us when we created the integration.

  1. Log into your Slack account in your browser and configure a new ‘Incoming Webhook’ integration. Choose a channel you want it to post to and change the name if you want, but for these purposes it isn’t necessary. When it gives you an Incoming Webhook URL, copy it somewhere safe.
  2. In your WordPress admin area, open the Contact Form 7 plugin and open the form you want to post to Slack from.
  3. Select the ‘Additional Settings’ tab.
  4. In your Additional Settings textarea, paste the following:
    on_sent_ok: "var name = jQuery('.slack-name').val();var email = jQuery('.slack-email').val();var occ = jQuery('.slack-occupation').val();var requestBody = "A request was made to join the Slack channel by: Name: " + name + ", Email: " + email + ", Occupation: " + occ + ".";jQuery.post('{{ WEBHOOK URL }}', 'payload={"channel": "#{{ CHANNEL TO POST TO }}","text": "' + requestBody + '" }');"

One important thing to note here is the on_sent_ok variable that we put before all of our custom code. This means that that JavaScript will only be processed after the form has sent, meaning we don’t necessarily need to worry about validating the field itself, if we’ve already handled that in the form.

After you’ve saved your form, you should see any form submissions pop up in the Slack channel until you remove the integration!

If upon browsing your WordPress blog or website you find a mostly blank page with an error message that says something like “Error Establishing Database Connection” it generally means that your MySQL database credentials changed, or your .htaccess file is corrupt.

Start out by verifying your MySQL credentials:

  1. Connect to your server via FTP and browse to the root of your site. This is where you’ll find folders like wp-content, wp-includes and wp-admin. Look for a file called wp-config.php and open it up.
  2. Look for the following lines:
    /** The name of the database for WordPress */
    define('DB_NAME', 'your_db_name');
    /** MySQL database username */
    define('DB_USER', 'your_db_username');
    /** MySQL database password */
    define('DB_PASSWORD', 'your_db_password');
    /** MySQL hostname */
    define('DB_HOST', 'your_hostname');
  3. Log into your cPanel or hosting panel and verify that:
    1. The database name that has been created for WordPress matches the DB_NAME.
    2. The username and password for the user associated with the WordPress table are both correct and have ALL Privileges on the table.
    3. Check the hostname that your hosting provider requires for WordPress. It defaults to localhost but this can be different depending on the host. For example, MediaTemple uses $_ENV{DATABASE_SERVER}

After you’ve completed those steps, try accessing your site again. If it still isn’t working:

Check for a corrupt .htaccess file

If you recently moved hosting providers or even just moved server to server, there is the possibility that a setting in your .htaccess file is breaking the rest of your WordPress installation.

  1. Connect to your server via FTP and browse to the root of your site. This is where you’ll find folders like wp-content, wp-includes and wp-admin. Look for a file called .htaccess and open it up.
  2. Look for anything above or below the #START WORDPRESS / #END WORDPRESS block of rules that looks out of the ordinary. I know that’s vague but it depends on the hosting set up. Keep in mind that some plugins like Yoast’s SEO and W3 Total Cache add rules to the .htaccess file and those rules should be left alone. If you see something like AddHandler php5-script .php try removing it, saving it to the server and reloading the site.

If neither of the above methods worked, it’s possible that your MySQL database has been corrupted in one way or another, or the name is invalid and you didn’t get any specific errors for that. In that case you may be better off doing an export of your MySQL database, and then dumping that database and creating a new fresh one.

To start with a fresh WordPress database:

  1. Log into your MySQL database using something like phpMyAdmin,  and select your WordPress database. Be sure to select the whole database, not just a single table inside. In the gray bar across the top of the panel select ‘Export.’
  2. When you export the database, select SQL as the type of export and save it to your computer.
  3. Create a new MySQL database with a new name, new user (with ALL Permissions on the database) and new password.
  4. Log into the new MySQL database and in the gray bar across the top of the panel, select ‘Import.’
  5. Select the export file you just saved to your computer, and import those tables to the new MySQL database.
  6. Open up your wp-config.php file as described above, and update the DB_NAME, DB_USER and DB_PASSWORD
  7. Upload the updated wp-config.php file to your server and log in to your (hopefully) fully functional WordPress site!

The above fixes should work in most cases, but if you’re stuck, confused or just don’t want to worry about breaking anything, I’m happy to help! Get in touch and we’ll get your site working ASAP.

Responsive Images are one of the next hurdles in making the web truly accessible to everyone. Without responsive images, even if we have a responsive site and the images ‘scale’ using CSS, if our visitor is using a phone or tablet they will receive the full resolution image that a visitor on a desktop would see.

While this might seem like a good thing in that the visitor will see the highest quality image, it results in a waste of bandwidth and a slow experience for the user. We don’t yet have a ‘native’ HTML or CSS solution to this. Well, technically we have the picture element but it’s browser support is, as of this writing, non-existent.

The main problem lies in the way that the browser loads each page. Smashing Magazine said it best:

The problem is that browsers are too quick for us! In order to provide the fastest loading time possible, browsers preload all of the images that they can identify in the source code before any CSS or JavaScript is processed.

So what does that leave us with? Well until the picture element receives support (here’s to hoping!), we need to find a solution that fetches an image based on the current users resolution. There are quite a few good plugins out there, but the one that I’ve found to be most effective for my needs is Matt Wilcox’s Adaptive Images.

One of the best things about Adaptive Images in my opinion is that, unlike the majority of the other plugins, you don’t need to change your markup at all. That means you spend less time installing and your code stays clean.

How to install Adaptive Images on WordPress

When I first went to install Adaptive Images on WordPress, I definitely ran into some trouble. The instructions don’t work the same way when applied to a CMS so some serious Googling was in order. Thankfully someone (thanks, Chris!) had beat me to the punch and worked out most of the kinks. If you want to read a much more detailed tutorial with some additional debugging info, check out Chris Ferdinandi‘s on the Github repo for Adaptive Images.

  1. First things first, go download the current version of Adaptive Images. (1.5.2 as of this post)
  2. !important (See what I did there?) Save a copy of your current .htaccess file in case things go pear-shaped. Do NOT simply replace your current .htaccess file with the one that Adaptive Images provides. WordPress and various WordPress plugins make edits to the .htaccess file so if you just over-write it with the .htaccess file from the Adaptive Images plugin, you’re gonna have a bad time.
  3. Open up your .htaccess file and look around for something like the following:
    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
  4. Right after RewriteEngine On, add the following:
    # Adaptive-Images -----------------------------------------------------------------------------------
      # Add any directories you wish to omit from the Adaptive-Images process on a new line, as follows:
         RewriteCond %{REQUEST_URI} !iwp-content/plugins
         RewriteCond %{REQUEST_URI} !wp-admin
         RewriteCond %{REQUEST_URI} !wp-includes
      # don't apply the AI behaviour to images inside AI's cache folder:
      RewriteCond %{REQUEST_URI} !ai-cache
      # Send any GIF, JPG, or PNG request that IS NOT stored inside one of the above directories
      # to adaptive-images.php so we can select appropriately sized versions
      RewriteRule .(?:jpe?g|gif|png)$ adaptive-images.php
      # END Adaptive-Images -------------------------------------------------------------------------------
  5. Save your .htaccess file and upload.
  6. Modify your breakpoints in adaptive-images.php and upload it to the root of your site. This is not the wp-content directory, it’s most likely simply named html
  7. Open up your header.php file and add the following before the wp_head() declaration:
        document.cookie='resolution='+Math.max(screen.width,screen.height)+("devicePixelRatio" in window ? ","+devicePixelRatio : ",1")+'; path=/';
  8. Upload header.php and test!

When testing, keep in mind that just resizing your browser won’t work. You’ll need to actually view the site on a smaller resolution device and inspect the image to ensure that it’s resizing properly.

Websites can sometimes be picky about the file-types that they are served. One issue that I recently discovered was that a stylesheet was using an .svg file as a background image for a few elements, but the elements would always have the ‘Broken Image’ icon displayed rather than the image.

This was happening even though I could see the .svg on the server, and the path was entirely accurate in the stylesheet. The error that the console gave me was:

Resource interpreted as Image but transferred with MIME type text/xml

It turns out that the HTTP headers were sending the wrong content along with the .svg. My website was receiving text/xml, but should have been getting image/svg+xml

The fix was simply adding the following rule to the .htaccess file in the directory that served the images. In my case this was the .htaccess file in the base directory of the WordPress installation.

AddType image/svg+xml svg

This tells the server to send .svg files with the mime-type image/svg+xml. After a cache and cookie clear in my browsers, the images appeared!

If you do add this to WordPress’s .htaccess file, be sure to add it after the WordPress rules. If you don’t, your site will likely suffer some unexpected consequences.

I recently saw something really cool over at http://css-tricks.com, which by the way is an excellent resource for all sorts of HTML/CSS/Javascript tricks and tips. If you go to comment on any of the individual posts, it will pop up a preview of what your comment will look like complete with your Gravatar, website URL, and comment text etc.

I really liked the way it worked and decided to take a shot at creating something similar. I was pleasantly surprised by how quickly it came together.

WordPress comments without preview

Boring, regular WordPress comments.

Fancy WordPress comment preview


Adding the proper HTML to your comments.php

We’ll need to add a bit of HTML to your comments.php to display the blank preview box, as well as the preview as you’re filling out the content box itself.

<div class="commentPreview">
  <h3>Comment Preview</h3>
  <div class="theComment">
    <?php echo get_avatar( 'email@example.com', $size = '75'); ?>
    <div class="preview-content">
      <div class="preview-meta">
        <a href="" class="preview-url"></a>, <?php echo get_the_date(); ?>
      <div class="preview-text">

This is just some basic HTML that tells the page to display an area of your page as a preview box. Nothing too magical happens here. We’re essentially just creating a box for the content to fall into.

You can style it up to match your theme or add elements as you see fit! The trickiest thing here is just the Gravatar line:

<?php echo get_avatar( 'email@example.com', $size = '75'); ?>

This tells WordPress to include a blank Gravatar by default. You can change the default image in your ‘Discussion’ Settings in your WordPress admin.

JavaScript for the Live Preview

Now for the real magic. We’ll be making use of jQuery and a nice Google Hosted JavaScript encryption plugin called Crypto-JS. Be sure to wp_enqueue both of these files properly in your functions.php! If you don’t know how to do this, check out my previous post on wp_enqueue’ing in WordPress.

Once you’ve enqueued the two scripts mentioned above, include the following JavaScript on the page below wherever you declare your jQuery. I would recommend having a separate file such as a ‘global.js’ that includes all of the JavaScript for your site.

If you don’t have that, you could include this code in your footer.php, header.php or comments.php as long as it’s below the references to jQuery and Crypto-JS.

jQuery(document).ready(function() {
    jQuery('.commentInput').each(function() {
    jQuery('.commentInput').change(function() {
      var author = jQuery('#author').val();
      var email = CryptoJS.MD5( jQuery('#email').val().toLowerCase().trim() );
      jQuery('.commentPreview .avatar').attr('src','http://gravatar.com/avatar/' + email);
      var url = jQuery('#url').val();
    jQuery('textarea.comment').keyup(function() {
      var comment = jQuery(this).val();

The only think you’ll potentially have to swap out here are #author, #email, #url and textarea.comment. Those are the identifiers that my comment form is using. You’ll need to look at the code to find the specific classes or id’s that your comments are using on the respective inputs.

Preparing the Document

Let’s go through the Javascript function by function:

jQuery(document).ready(function() { });

This function tells your code to be prepared to run by the time the DOM is ready. It’s important to wrap your Javascript/jQuery in this to prevent script collisions. But wait, why are we using jQuery rather than $?

Essentially, WordPress is already using the typical jQuery $ in another scripting library, so it won’t work to preface your jQuery scripts with it. Therefore we need to use jQuery as our element selector.

Clearing any leftover data

jQuery('.commentInput').each(function() {

Here we iterate through each of the comment form inputs that have a class ‘commentInput.’ Then for each of those we set a blank value. This is like a reset on the form, so that it works consistently from page to page.

Capturing the Author, Email and URL

jQuery('.commentInput').change(function() {
  var author = jQuery('#author').val();
  var email = CryptoJS.MD5( jQuery('#email').val().toLowerCase().trim() );
  jQuery('.commentPreview .avatar').attr('src','http://gravatar.com/avatar/' + email);
  var url = jQuery('#url').val();

This portion is relatively straightforward. First, we look for a change on any of the inputs with the class ‘commentInput.’ Then if there is a change, we set variables for author, email and url containing the respective value of each of the inputs.

To add the ‘author’ portion of the preview, we simply add the value of author to the HTML element we created above with the class ‘preview-url’ using jQuery’s .text().

To add the ‘url’ portion of the preview, we want to replace the default blank href attribute with the URL that the user has entered. We’ll do this using jQuery’s .attr().

The toughest portion of this function is the email. Gravatar requires the email to be lower case, trimmed (no white space before or after) and then hashed using MD5. Unfortunately JavaScript doesn’t include any built in encryption for MD5. Thankfully, CryptoJS exists.

var email = CryptoJS.MD5( jQuery('#email').val().toLowerCase().trim() );

So reading from inside to out, we’re going to take the value of the input with the ID ’email’, then we’ll lower case the value, and trim all white space before and after. Then we’ll wrap the whole shebang in CryptoJs.MD5();.

This returns a MD5 hash of the string that the user entered so that we can grab their avatar from Gravatar.com! Thankfully the URL structure for the avatar is pretty simple. We’ll just use .attr() again and set the src attribute to contain ‘http://gravatar.com/avatar/MD5-Hashed-Email.’

The comment message

jQuery('textarea.comment').keyup(function() {
  var comment = jQuery(this).val();

The comment message is a little different. With the various inputs we just wanted to capture the input on a change. This is because we don’t want incomplete data for something like the email or URL. However with the comment itself, we’d like it to show up as the user is typing!

So for that we’re going to use a keyup function. This runs every time a key is released inside the textarea, thereby providing a real-time preview of what the comment will look like!

You’ll notice that we’re also entering this text into the comment area using .html() rather than .text(). This is more for looks than anything else. This way if a user enters a link or bolds some text in their comment using HTML it will carry over to the preview.

And there you have it! Comment previews that update dynamically as the user is typing the comment! This clearly doesn’t watch for validation or anything like that, and is intended more for the purpose of demonstration than anything else.

You can also check out the code’s GitHub repo if you want it all at once!

So what do you think, would you like to see a preview of your comment as it’s being typed? If you want to see this in action, check it out on any of the posts pages on Molliepop.com!

WordPress 3.7 is out and while it may not look all that different, we’re all better off for it. There’s an excellent article on Post Status about the update, so I won’t go into too much detail but there are some exciting changes in this newest update.

Automatic (and seamless) Background Updating

WordPress now comes with background updating out of the box. This is a wonderful new feature and something that I’ve been eagerly anticipating for a while. I hate going through all of my WordPress sites and manually backing things up, and updating each site one by one. It may seem a trivial task, but if you have more than one or two WordPress sites it can be a real time sucker.

This automatic background updating comes with a few caveats, however. For example, by default it will only update to security releases (eg: 3.7.0 to 3.7.1) and it will not automatically update to a new version (eg: 3.7 to 3.8). This is for fairly obvious reasons such as, WordPress doesn’t want to be responsible for breaking your damn site. However if you feel like living on the wild side, you’re free to add the following to your wp-config.php.

define( 'WP_AUTO_UPDATE_CORE', true );

That tells WordPress to go ahead and throw caution to the wind and just update the damn core while it’s updating everything else! Note that I don’t recommend this on a clients site. If it’s your own site, then whatever. That’s your prerogative.

You can also do some cool things like auto updating (many, but not all) plugins and themes using auto_update_theme and auto_update_plugin. But you can read more about that in the Codex.

Better Search Functionality

WordPress search has (historically) sucked pretty hard. Don’t get me wrong, it works…alright…sometimes. Essentially up until now it’s been ranked more on publish date than post relevance. All of that has changed with Basie and we’re finally going to be seeing better search. This is super important for sites that have a ton of content, so an updated search feature is more than welcome.

I’ve been tossing around the idea recently of a plugin for extending the search to query the database asynchronously and provide on page results without loading a new page, ala Google Instant Search. Generally you don’t want your search pages indexed anyway. It may be out of my immediate wheelhouse but I may give it a go anyway.

But that’s not all, folks!

While those are the two features I’m most excited about, there are a ton of new and improved things in Basie like an improved password meter, better language packs, improved inline documentation and so much more. You can read more about everything at Post Status, as I mentioned above.

WordPress thumbnails (or Featured Images) are a great way to show a single image from a lot of posts at once. This has a lot of applications but the most popular is probably the related posts plugin. You know what I’m talking about, it’s usually at the bottom of a post on any given blog and has 3+ other posts that you might be interested in. Usually just with an image and the post  title.

WordPress Related Posts

It usually looks something like this…

Featured posts plugins use the featured image from any given post rather than crawling each post to try to find the first image in the individual post. Oftentimes this won’t work out of the box if you’re using or creating a custom theme because the post thumbnail functionality needs to be added in your functions.php.

Step 1. Adding the theme functionality

It’s simple, really. First look in your functions.php for this line:

add_theme_support( 'post-thumbnails' );

If it’s there, awesome, move to the next step. If you can’t find it, simply add the following:

if ( function_exists( 'add_theme_support' ) ) { 
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 150, 150, true ); // Set your thumbnail size here, this will resize then crop.

This little chunk of code checks to see that the add_theme_support function exists and if it does, creates theme support for the post thumbnails. Pretty self explanatory.

Step 2. Adding thumbnails to your site

So you have thumbnail functionality, now what? Well if you just wanted to use them for related posts then download a plugin like nRelate and be on your way! If you’re looking for something more detailed, such as displaying the post thumbnail next to each post in the blogroll, then you’ll need to add something to the loop.

Adding the Featured Image next to each post

To add the Featured Image/thumbnail next to each post in the loop, first you have to decide which page you want it on. Do you want to have the images display on the ‘standard’ blogroll? If so, you’ll be editing ‘index.php.’ Do you want to have the images display only on the category pages? If so, you’ll just edit ‘category.php.’

Once you know what page you want to edit, open it up. You’ll want to place your thumbnail code somewhere between:

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


<?php endwhile; ?>

Once you’ve found the proper spot to add it (I tend to add it immediately after the opening while() statement), just add the following:

<?php echo get_the_post_thumbnail($page->ID, array(150,150)); ?>

If you want to change the size of the image, you’re free to do so here, just edit the values in the array (width,height).

So now your index.php or category.php loop should look something like the following:

<?php if (have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
    <div class="post">
        <?php echo get_the_post_thumbnail($page->ID, array(150,150)); ?>
        <h2><?php the_title(); ?></h2>
        <?php the_excerpt(); ?>
<?php endwhile; ?>
<?php endif; ?>

Clearly this is a very stripped down loop, but you get the gist.

Adding a Featured Image to each post page

Sometimes if you order articles through a third party such as Brafton, they’ll automatically assign a featured image without putting any images in the blog content itself. This could cause confusion in your readers when they see images with the posts either through your related posts plugin, or next to the articles as I showed above, but then they visit the post itself and there is nothing but text.

So what’s a poor sucker to do? Go through each post individually and add links to all of the images one by one? No way, thankfully you can output the featured image directly on the post page. It’s actually remarkably similar to how we did it earlier. The only difference is that you’ll be editing ‘single.php’ and you’ll probably want to increase the image size so it makes more sense as the single image on the page. So your ‘single.php’ should end up looking something like this:

<?php if (have_posts()) : ?>
<?php while(have_posts()) : the_post(); ?>
        <?php echo get_the_post_thumbnail($page->ID, 'medium'); ?>
        <h1><?php the_title(); ?></h1>
        <?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>

The primary difference here is that I’ve used a keyword (medium) rather than putting in the dimensions. Either way works though. You can read more about the featured image/post thumbnails in the Codex. As always, drop any questions below!

I’ve been working with WordPress on a strictly theme development basis for about 2 years now. I’ve edited and created countless CMS’s out of various WordPress themes and even authored 4 or so myself.

I’ve always stuck away from plugin development because I generally don’t like the concept of plugins.

Why the hell would I want to dirty up my clean website with someone else’s code that might be good, but might suck? Beyond that I do have some control over it, but not much and excessive plugin use (if poorly coded) totally slows down WordPress sites. Therefore I’ve always kept my plugin use on sites I manage to a minimum, Yoast for SEO, Akismet for spam, W3 Total Cache for speed etc.

I don’t mean this in a negative way. WordPress wouldn’t be nearly as popular or robust as it is without the amazing community of developers creating plugins and core updates, it just means I’m an overly cautious sometimes cynical developer.

All that to say, I’ve also been a bit nervous to develop plugins. The concepts, actions and hooks have always scared me a bit because I didn’t know them and I was comfortable with the theme development. Plugins are a whole new wrinkle.

But this weekend I be like, caution be damned…I’m doing this. So I started developing my very first plugin. It’s just a little writing prompt helper that I may or may not even release to the public, but it’s good to at least put yourself out there.

Anyway, I was working on this plugin over the weekend in our spaceship without any internet (not an easy task) and kept getting this error:

Notice: wp_register_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks.

Not to mention that, but nothing was working. I couldn’t get any stylesheets or scripts to enqueue for the life of me, which was seriously cramping my style!

I checked, double and triple checked my plugin code and for the life of me could not figure out why this was coming up. I was using add_action('admin_enqueue_scripts', 'my_function_name') to enqueue my scripts in the plugin so why in the world was this error coming up?

Well turns out I had been enqueueing improperly. I had been registering and enqueuing scripts using WordPress’s functions, but I was never hooking them properly. What I was doing was:

 // Registered scripts...
 wp_register_script( 'jquery', '/wp-includes/js/jquery/jquery.js', '', '', true );
 wp_register_script( 'typer', get_template_directory_uri().'/js/jquery.typer.js', array('jquery'), '1.0', true );
 wp_register_script( 'global', get_template_directory_uri().'/js/global.js', array('jquery'), '1.0', true );
 // And then loaded them...
 wp_enqueue_script('typer'); ?>

And that was it. Little did I know that I also needed to wrap all of that in a function just like I did when I enqueued my scripts for my plugin. Therefore:

function my_scripts() {
 // Registered scripts...
 wp_register_script( 'jquery', '/wp-includes/js/jquery/jquery.js', '', '', true );
 wp_register_script( 'typer', get_template_directory_uri().'/js/jquery.typer.js', array('jquery'), '1.0', true );
 wp_register_script( 'global', get_template_directory_uri().'/js/global.js', array('jquery'), '1.0', true );
 // And then loaded them...
add_action('wp_enqueue_scripts', 'my_scripts');

Fixed everything! Learn from my mistake…just enqueue properly and your life will be better and you’ll save ages of digging around for help.

By default, WordPress will display comments in an oldest to newest fashion. This is great for comments that are children or in reply to other comments because you would want to go down the conversation chain in chronological order.

However if you’re running a blog or have a custom testimonials page or something like that and would prefer the comments to go in reverse chronological order, WordPress has you covered.

By now you should be using the wp_list_comments() function to be outputting your comments. It’s been available since WordPress 2.7 and at the time of writing this, we’re currently at 3.6.

Assuming you are using comments the ‘right’ way, look at  your comments.php in your theme folder for the following:


What we need to do is place the $reverse_top_level parameter inside those parentheses, and set it to true. It should look something like this:


If you’re already using other parameters inside the function, it may look something like this instead:


Voila! You’re finished.

Wait, what’s that? You aren’t using wp_list_comments()? Well get with the program! Nah, don’t worry. There is a solution for you as well. What you’ll be looking for in your comments.php is a line something like this:

foreach ($comments as $comment)

Simply change it to:

foreach (array_reverse($comments) as $comment)

And you’re golden! Admittedly this is the ‘hackier’ way of doing it, so I really would recommend using the proper functions provided by WordPress.

Check out the function reference that I mentioned above for a bunch of other cool things you can do with your comments like setting the avatar size, the amount per page and a crapton more.

WordPress is fantastic. It’s grown well past it’s infancy of a simple blogging software into being capable of acting as a full fledged Content Management System.

Google Analytics is equally awesome. It’s an excellent way of tracking visitor flow throughout your website, identifying how people are arriving and why they leave and so much more. Best of all? They’re both free.

One potential downside of Google Analytics, however, is that it shows ALL traffic. That includes you and any other people that may be involved in editing your blog or business’s website! It does allow you to filter out by IP addresses, but that only works if you have static IP addresses which most people (especially if you aren’t a business) won’t have.

Thankfully if you’re using WordPress, there’s a simple fix! Traditionally you would install Google Analytics by creating your account with Google, setting up the site in their panel and then copying and pasting code that looks something like this into your footer:

(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

ga('create', 'UA-XXXXXXXX-X', 'example.com');
ga('send', 'pageview');


Why the footer? Best practice right now says that all Javascript and other code functions should be placed as close to the bottom of the website as possible. This prevents the page from not appearing at all if scripts hang among other potential issues. Of course, you CAN place Javascript/jQuery references in the header or anywhere else on the page, but in most cases, it would be best if you didn’t.

So with WordPress, to avoid tracking anyone that is logged into your site (you, your editors, etc.) simple wrap the tracking script in a php ‘if’ statement:

<?php if ( !is_user_logged_in() ) {?>
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

  ga('create', 'UA-XXXXXXXX-X', 'example.com');
  ga('send', 'pageview');

<?php } ?>

The key here is the if statement. We’re using the


function provided by WordPress which does exactly what it sounds like…tests if the current user is logged in. If they are, it will not display the Google Analytics information and dilute your website traffic statistics. You can read more about it in the WordPress Codex.

This works great for our Google Analytics scenario, but what if we allow open registration on our website? In that case we’ll layer on another conditional statement using the user permissions test.

<?php if ( !is_user_logged_in() && !current_user_can( 'publish_posts' ) ) {?>
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

  ga('create', 'UA-XXXXXXXX-X', 'example.com');
  ga('send', 'pageview');

<?php } ?>

Clearly this is a little bulkier, but the basic principle remains the same. If the user is not logged AND the user can not publish a post, then display the tracking script!

Using conditional statements like these are what make WordPress so flexible and powerful. There are many other applications for the if statements used above, but refining your Google Analytics results is a good place to start. If you have any questions feel free to drop them in the comments below!