What the Queries

I’ve never been a fan of IDEs, complex debugging tools with breakpoints, variable watch lists and all that fancy stuff. var_dump() and print_r() have always been my best friends.

Recently I was playing around with the caching arguments in WP_Query, trying to combine that with update_meta_cache() while sticking wp_suspend_cache_addition() somewhere there in the middle, and it quickly became a mess, so I wanted to know what queries am I actually running under the hood.

I came up with this little piece, which I think I’ll use more often from now on:

// Assuming SAVEQUERIES in set to true.
$GLOBALS['wpdb']->queries = array();

// All the magic goes here

var_dump( $GLOBALS['wpdb']->queries );

This gives you a nice list of SQL queries that were triggered only by that magic code in between. Works great when you need a quick sanity check on all those caching arguments, priming meta or term caches, splitting queries and whatnot.

Obviously it empties the initial set of queries, so anything in Debug Bar, Query Monitor, etc. will no longer be accurate.

What’s your favorite way to keep track of queries?

How to: Disable HTTP Calls in WordPress

Sometimes you’re travelling on a plane or on a boat, in the metro or on the road. Sometimes you just have a crappy Internet connection, and you’ll notice that a local WordPress install (mostly admin pages) takes several seconds to load. That could create a big problem if you’re developing a theme or plugin, and have to refresh eighty times per minute.

WordPress uses its HTTP API (the WP_Http class and wrapper functions) to look for plugin, themes and core updates, fetch RSS feeds or talk to third party API (such as a Twitter widget plugin) and with no Internet connection, calls to such functions will timeout in a few seconds, thus the long page load time. A simple solution is to simply disable all HTTP calls and luckily, WordPress allows us to do that in a single filter for our theme (functions.php) or plugin file:

add_filter( 'pre_http_request', '__return_true', 100 );

The smarter way would be to intercept the request and let it pass or block it based on the request URL, that way you’ll be able to work with local APIs. Yet another benefit of using the WordPress HTTP API and not file_get_contents or curl_exec :)

Update: As Dion Hulse mentioned on Twitter, you can also use WP_HTTP_BLOCK_EXTERNAL in your config file to achieve the same thing, but in a more “cron friendly” way. More information about this can be found somewhere around this line.

Native Image Sizing “On the Fly” with WordPress

I tweeted it out not too long ago, and it seems to have gotten people’s attention. So why do WordPress theme developers still use TimThumb? One of the valid reasons seems to be dynamic image sizing. Of course if you’re using TimThumb for post thumbnails in your theme, your life saver is the add_image_size function — you don’t need “dynamic resizing” since all your thumbnails are of equal sizes throughout your theme.

However, the valid reason I seem to have bumped in, is the fact that sometimes you would want to use a specific size for an image, but only once, for one post or page. The add_image_size function here will add a lot of overhead, crunching all the uploaded images into the size you want to use only once. Like a shortcode that can resize and crop an image from your media library to whatever dimensions you tell it to:

[image src="http://example.org/wp-content/uploads/2012/03/image.png" width="150" height="150"]

Right, a shortcode (argh!) to dynamically resize an image. Fair enough, a lot of premium themes seem to have something similar, but mostly use TimThumb because it’s so simple. However, I’ve created an image shortcode function that resizes and crops images from the media library on the fly using the image_make_intermediate_size function available as early as WordPress 2.5!

It saves the resized image on disk, and returns the absolute URL to that image. Of course you’d want to add things like captions, alt tags and so on, but the basic idea is there. Why is this better than TimThumb?

  • It stores the image files on disk and uses absolute URLs to those images, meaning you won’t have problems hosting your thumbnails on a CDN.
  • It uses functions native to WordPress and works with the WordPress media library, so extra files are deleted when an attachment is deleted — no more junk in your cache/folder.
  • It doesn’t have a zero-day vulnerability :)

There are drawbacks too, like the fact that it’s a shortcode! Although I’m pretty sure we can use the same technique and hook it directly to the content, bypassing the shortcodes madness. Oh, and it doesn’t support remote files too, only the ones in your media library, but that’s a good thing, as we have all figured out by now.

Feel free to fork the Gist on Github and experiment with the code, I’m sure you can think of how to make it better, easier to use and faster. Thoughts and comments welcome, and thank you for stopping by!

How to Get the Current URL in WordPress

Here’s a quick tip! I was wandering around the web for the perfect solution to retrieve the current URL in a WordPress theme or plugin. I found a bunch of solutions for PHP, but not directly related to WordPress so I thought there has to be an easier way, and after a few hours of examining with global variables seems like I found it.

global $wp;
$current_url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );

Beats all the $_SERVER approaches and no need to identify whether the host is using SSL, etc. You can add a trailing slash to that with trailingslashit if you need to, and it looks much cleaner too. Hope you enjoy that, and thanks for tweeting ;)

Change the year of all posts in a particular category to 2012

Snippet! Change the year of all posts in a particular category to 2012 with a single SQL query (use with phpMyAdmin or the MySQL command line interface)

UPDATE wp_posts AS p
  JOIN wp_term_relationships AS tr ON tr.object_id = p.id
  JOIN wp_term_taxonomy AS tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
  JOIN wp_terms AS t ON tt.term_id = t.term_id
  SET p.post_date = REPLACE(p.post_date, YEAR(p.post_date), 2012)
  WHERE t.slug = 'my-category-slug' AND tt.taxonomy = 'category';

Obviously replace my-category-slug with the category you’d like to target and perform the same magic on the p.post_date_gmt field. Not entirely sure why you would use such a technique, but it was asked by Jim Edwards on Twitter.

Varnish and Preview Posts in WordPress

I wrote earlier that I started playing around with Varnish here on my site and that post has a little snippet that strips all incoming and outgoing cookies (except the admin of course.) Today I stumbled on a problem where I had no permission to preview a post I was drafting in WordPress and they all turned 404’s when I tried to.

I first thought Varnish was stripping out the preview query string but I was wrong, the problem was that WordPress knew I was logged in and editing the post when I were in the admin panel, but when I tried to preview it on the front end Varnish was stripping out my login cookies, hence it didn’t display my draft post.

Here’s a snippet for vcl_recv and vcl_fetch that should go before the unset cookies statement which passes the request to the web server if preview=true is found in the request URL.

if (req.url ~ "preview=true") {

Restart the Varnish service and voila! Your cookies aren’t stripped out anymore and you can now preview your posts and pages. Do note though that if somebody manually types in the preview query string in the browser, they’ll by-pass Varnish as well.

Attachments Filename and Directory in WordPress

I was trying to figure out how to get the absolute directory of an attachment post in WordPress. Turns out there’s no easy function that can give you one, but there is one called wp_upload_dir which will give you an array of the upload directories and URLs. So here’s the secret sauce:

$url = wp_get_attachment_url( $post_ID );
$uploads = wp_upload_dir();
$file_path = str_replace( $uploads['baseurl'], $uploads['basedir'], $url );

The $file_path variable will now contain an absolute path (filesystem path, not URL) to the location of your attachment file. You can then use it when sending attachments with wp_mail or perhaps when serving the file dynamically. Enjoy!