Archive for the ‘Web Development’ Category

Using Custom Post Meta to Retrieve WordPress Posts

Sunday, March 4th, 2012

The other day, I was in the process of setting up some custom post meta for an event post type. I needed to add a start date/time and an end date/time for the event as custom meta information. Once I got all of that set up, I needed to modify the loop so that it retrieved the events in order of their start date/time; but I also needed to make sure I only retrieved events that hadn’t yet ended (based on their end date/time).

In the past, this wasn’t really possible with WordPress. You could either order posts by a custom meta value, or you could limit your query to posts that had a specific custom meta value, but you couldn’t do both. Then, in version 3.1 of WordPress, the meta_query was introduced to the WP_Query class. Now, however, you can use the traditional orderby and meta_key properties to sort your posts by a specific meta value; and you can use the meta_query property to limit the posts that are returned.

In my case, wanting to sort the posts in ascending order according to the start date/time (which is stored in the MySQL datetime format of YYYY-MM-DD HH:MM:SS) and wanting to limit the posts to items that had an end date/time that had not yet occurred, I used the following properties:

array(
    'orderby' => 'meta_value',
    'meta_key' => '_event_start',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => '_event_end',
            'value' => current_time( 'mysql' ),
            'compare' => '>=',
            'type' => 'DATETIME',
        ),
    ),
);

If you need to sort your posts according to a numerical value, you should use meta_value_num as your orderby property instead of using meta_value. For instance, if I was storing the start and end date/times as Unix timestamps instead of MySQL datetime values, I would have needed to use meta_value_num to get them back in the correct order.

Related posts:

  1. Importing Posts From Custom Sources Into WordPress
  2. WordPress: Adding “Page Links To” to Custom Post Types
  3. WordPress: Adding “Get Shortlink” to Custom Post Types

HTMLCenter Web Development Blog

HoverIntent in WordPress

Wednesday, February 29th, 2012

Whenever you’re working on a new WordPress theme that includes hover (mouseover) effects, especially dropdown or flyout menus, you might want to include hoverIntent. HoverIntent is a term that describes a concept through which you delay a hover action until a certain amount of time has passed, in order to make sure that the user really intended to trigger that action.

We’ve all been on websites with dropdown menus that tend to get in the way of the content, and pop open as soon as your mouse touches even a small portion of them, and we’ve most likely all been annoyed by it. The idea behind hoverIntent is to measure the speed of the mouse movement, attempting to determine whether the user actually intended to stop on the item or not. If the mouse just moves over an item with a hover effect, but doesn’t stop on it, the hover effect should not be triggered; if, however, the user’s mouse does slow down enough or stop on the item, the hover effect should be triggered.

Back in 2007, Brian Cherne submitted the first version of a jQuery plugin attempting to fix this issue. The plugin was called hoverIntent, and has become somewhat synonymous with the usability concept discussed above.

The WordPress gang was actually fairly quick to pick up on this, and began including Brian’s hoverIntent plugin in the WordPress core when WordPress 2.7 was released. That’s right, hoverIntent has been part of the WordPress core since December 2008.

However, until version 3.3 of WordPress, the hoverIntent script was only registered in WordPress from within the admin area; it wasn’t readily available (without using wp_register_script() to register it yourself) on the front-end. As of version 3.3, though, the registration of hoverIntent was moved outside of the admin area so that it is easily available throughout a WordPress site, on the front-end and back-end.

To use hoverIntent, you simply need to enqueue it by using wp_enqueue_script( 'hoverIntent' ) or even by including the handle ‘hoverIntent’ in the list of dependencies when registering your own script file in your theme or plugin.

Then, if you want to actually apply hoverIntent to an element in your theme or plugin, you simply need to call it from within your JavaScript. To use hoverIntent, you simply call jQuery( [selector] ).hoverIntent( [over-callback], [timeout], [out-callback] ).

Normally, for accessibility purposes, you should use hoverIntent as an enhancement for normal hover effects, ensuring that the hover effect doesn’t stop working altogether if JavaScript fails. Therefore, you probably want to include a default hover effect that occurs without JavaScript, then add a delay to that effect with the hoverIntent method.

To do that, though, you’ll need to use some JavaScript to determine whether or not JavaScript is active on the page. Usually, you do this by adding a CSS class to the body element that then gets removed by JavaScript.

For instance, the initial HTML for your body element might look like:

<body class="no-js">

Then, within your JavaScript file (assuming you have jQuery enabled, which is required in order to use hoverIntent), you would add a line that looks something like:

jQuery( function( $ ) {
$( 'body' ).removeClass( 'no-js' );
} );

Then, your CSS would look something like:

a:focus,
.no-js a:hover,
a.hover {
text-decoration: underline;
}

and your call to hoverIntent would look like:

$( 'a' ).hoverIntent( function() { $( this ).addClass( 'hover' ); }, 100, function() { $( this ).removeClass( 'hover' ); } );

Now, normally you wouldn’t use hoverIntent to simply add or remove an underline from a link; but the concept remains the same no matter what hover effect you’re applying.

Related posts:

  1. Using Google’s CDN for WordPress JavaScript
  2. Using Javascript in WordPress Themes
  3. Quick Tip: WordPress Visual Editor Button Icons

HTMLCenter Web Development Blog

Getting the Most Out of QR Codes Using URI Schemes

Thursday, February 23rd, 2012

Advertise here with BSA

Getting the Most Out of QR Codes with URI Schemes

Lately, everyone has been talking about the potential of the QR code. It has become the Internet’s equivalent of traditional barcodes (like those you’d find on physical goods at your favorite retail store).

Someone can take a quick snapshot of a QR code with their smartphone and immediately have a website up and loaded, so we could print QR codes on paper and physical goods such as business cards, magazine ads and posters in order to lead people to our site.

But, more often than not, web developers don’t use QR codes to their fullest potential.

In this article, we’ll discuss a technique that will unlock the full potential of QR codes through URI schemes.

How QR Codes Work in a Nutshell

Let’s learn how the QR code mechanism actually works. QR codes, at their core, are specially generated images that work like barcodes.

Certain commands (known as responses) are built in, and when a QR code is captured by a camera (usually one on a smartphone or tablet), the image of the QR code is processed and then the built-in response is carried out.

A common QR code response is to open a certain website in a web browser on the device that captures the QR code.

QR codes look like the above and contain information that can be captured by a camera and interpreted by a smartphone, tablet or computer.

QR-Code Readers

This is where things get interesting. QR-code readers — the apps that scan the codes and perform the actions — are not equal when it comes to functionality. Some are able to recognize QR codes and do all sorts of amazing things, and others can simply open URLs or display text.

Most smartphones have the same set of basic features (address book, calendar, texting functionality, alerts and Internet browsing), and a good QR-code reader can cater to all of those.

With low-functionality apps in the mix, though, URL-opening is likely the only reliable function that we can expect most QR-code readers will have.

Here’s a list of features that QR-code readers are generally equipped with:

  • Displaying text
  • Setting up system alerts
  • Adding events to calendars
  • Opening URLs in a browser
  • Collecting contact information (including vCards)
  • Sending email
  • Sending text messages (SMS)
  • Geolocation
  • Calling other phones
  • Connecting to WiFi

The Idea: Using URI Schemes

Since browsers can already launch default email clients via a simple mailto URL (browsers have supported URI schemes like these for years), could the same technique be used to offer in-app functionality for other products that have non-native URI schemes and that a QR reader wouldn’t support by default?

The answer is yes!

If the application supported the scheme, and if the user had the app the QR represented installed, it would work beautifully — and it wouldn’t matter which QR-code-reader was used.

The Possibilities

Here’s a list of some cool things that are possible:

  • Launching native Apple apps (Mail, Phone, FaceTime, Text, Map, YouTube and iTunes)
  • Running JavaScript bookmarklets
  • Opening certain IM clients (Skype, AIM, MSN, GTalk, ICQ and Yahoo)
  • Opening special applications (IRC tools, feed readers, FTP clients and SVN repositories)
  • Opening any application that registers a URI scheme when it installs on a platform

What makes this particular technique so amazing is that it doesn’t rely on the QR-code reader being very advanced; all it needs is for the app creator (be it Skype, Evernote or Angry Birds) you want to launch and interface with to use the system development API to register a URI scheme.

In the case of Apple, it’s the Cocoa Touch OpenURL method of the shared UIApplication object, and for other platforms (like Android), there will be an equivalent somewhere in the documentation.

From scanner to browser to application — the possibilities are endless!

Below is a list of some common non-http URI schemes:

Application URI Scheme or Protocol Query Strings
Default e-mail application mailto:<email>?query Subject
CC
BCC
Body
Default phone application tel:<number> N/A
Default SMS application sms:<number> N/A
Chat Room client irc://<url>:query port
channel
password
Syndication feed reader feed:<url> N/A
Apple FaceTime facetime:<number> N/A
Skype client skype:<username|number>?query add
call
chat
sendfile
userinfo
Google Talk client gtalk:query?<email> chat
call
Windows Live Messenger client msnim:query?<email> add
chat

voice

video

Yahoo! Messenger client ymsgr:query?<email|number> sendim

addfriend

sendfile

call

callPhone

chat

im

customstatus

getimv

AOL Instant Messenger client aim:query?<username> goim

goaway

addbuddy

What does this mean for us? As it stands, there are actually quite a number of applications for the desktop (as well as mobile), which already use URI schemes.

Take Skype, for instance. Do you want people to be able to capture a QR code that causes their phones to call you via Skype on their handsets? That can be done (at least on iOS) right now.

It can also be used to run several native apps, launch JavaScript bookmarklets (perhaps including apps that run within browsers) and access the usual FTP and IRC protocols (if associated with something).

Here are some useful links for developers:

Now that you know a bit more about QR codes and have gotten a brief overview of things you need to know to get started, I’ll outline the steps to the technique below.

Note: The technique I’ll be describing below can even be used to execute JavaScript code, so under the wrong set of code-writing fingers, this could be exploited.

Step 1: Choose the Response You Want to Perform

First, decide what you’d like the QR code to accomplish. Obviously, you can use the regular QR-code generator stuff — like sending text messages to phones or sending emails — but let’s try something trickier.

We’ll create a Skype QR code that will automatically launch the app and make a voice call to a Skype contact. (This will only work if the user that scans the QR code has Skype installed).

Step 2: Create a URL Using a URL-shortening Service

Many QR-code generators suffer from a particular problem: if you try to put a mailto or other non-http link into them, they sometimes think that an error occurred (this also affects some reader apps).

This, of course, won’t get our Skype launcher anywhere near being cross-QR-code-reader-compatible, so we need another solution — and, luckily, a common one exists that can help get this URL into the browser (and help web developers monitor click stats too)!

We’re going to use a URL-shortening service. These services are rarely fussy about what you insert into them, and they push out well-formed URLs with the HTTP header required for best-possible compatibility (most QR readers know how to open basic URLs).

A URL-shortening service such as TinyURL will turn that unconventional URL into a generally acceptable one.

For this QR, we’ll call the Skype contact named echo123 — this contact is the free voice-quality testing contact that Skype offers.

For our URL-shortening service, I’ll use TinyURL, but you can use one of the many other URL-shortening services out there such as bitly, is.gd and so on.

Just enter your chosen URI scheme into the shortener.

This is the result of my TinyURL link conversion:

URL skype:echo123?call
To http://tinyurl.com/echo123skype

If you click on the URL above, you might see something like the following (if you’re using Google Chrome on Windows):

Step 3: Generate the QR Code

Now take that generated URL — which will actually work if you have the desktop version of Skype installed for Windows or Mac — and generate a working QR code from it.

Check that the shortened URL works in your web browser; the link should launch Skype.

There is an abundance of choice when it comes to ways of generating QR codes; free tools exist all over the Web.

Below are a couple of free generators:

After you’ve generated your QR code, test it. Download one of the available applications for your mobile device (if you don’t already have one) and take a snapshot of the QR code you’ve produced.

Below are some free QR-reader products for mobile platforms:

What should happen, if you followed the instructions correctly and if you’ve got the Skype app installed, is this:

  1. Your QR code will be identified by the QR reader app
  2. The QR reader app will notice that the QR code contains a URL (thus it will skip the compatibility quirks of the readers)
  3. The TinyURL link will open in the default browser
  4. It will redirect to the Skype-call URI scheme and launch Skype

Pretty amazing stuff for one clever image!

The only thing left to do with your wonderful creation is to upload it to the Web (as I have with the finished example below). I recommend, as a best practice, that you consider providing a link to the URL being snapped in the QR image itself (for desktop users).

Beyond that, you could spruce up your QR codes with a bit of color or some limited artwork if you’re feeling extra creative.

The Finished QR Code

The above QR code will call echo123 on Skype if you have the app installed.

Conclusion

The power of this technique rests in the opportunity it gives designers and developers. A URI scheme exists between app developers and the browsers that support them (luckily, that’s all of them!).

Using a simple redirect (provided by you or a third party) and these already existing and well-supported features, you can launch applications, interact via query codes, execute JavaScript and do all sorts of wonderfully creative things.

QR codes are being increasingly adopted and have never been more widely used. With this single technique you can break past most existing limitations.

Related Content

About the Author

Alexander Dawson is a freelance web designer, author and recreational software developer specializing in web standards, accessibility and UX design. As well as running a business called HiTechy and writing, he spends time on Twitter, SitePoint’s forums and other places, helping those in need.


Six Revisions

Using jQueryUI in WordPress

Tuesday, February 21st, 2012

With the update to WordPress 3.3.x, the WordPress core now includes the entire jQueryUI suite packaged in the download. No longer do plugin and theme developers have to include their own custom builds of jQueryUI elements (hopefully they never did include custom builds of the elements, but there are quite a few plugins and themes that did). Instead, you simply need to enqueue the existing scripts.

Following is a full list of the jQueryUI elements included in WordPress, along with their “handles” for use with the wp_enqueue_script() function.

  • UI Core
    • Core – jquery-ui-core
    • Widget – jquery-ui-widget
    • Mouse – jquery-ui-mouse
    • Position – jquery-ui-position
  • Interactions
  • Widgets
  • Effects
    • Effects Core – jquery-effects-core
    • Effects “Blind” – jquery-effects-blind
    • Effects “Bounce” – jquery-effects-bounce
    • Effects “Clip” – jquery-effects-clip
    • Effects “Drop” – jquery-effects-drop
    • Effects “Explode” – jquery-effects-explode
    • Effects “Fade” – jquery-effects-fade
    • Effects “Fold” – jquery-effects-fold
    • Effects “Highlight” – jquery-effects-highlight
    • Effects “Pulsate” – jquery-effects-pulsate
    • Effects “Scale” – jquery-effects-scale
    • Effects “Shake” – jquery-effects-shake
    • Effects “Slide” – jquery-effects-slide
    • Effects “Transfer” – jquery-effects-transfer

There is one caveat, though. As of right now, WordPress does not include any CSS for many of these jQueryUI elements. Instead, you will have to temporarily include your own. I honestly couldn’t recommend the best way to do this. It seems to me that the best way is probably to download the appropriate CSS for each element and save them as separate CSS files, then register and enqueue them as they are necessary.

The WordPress team is working on putting together complete jQueryUI themes for the WordPress admin area, so you probably won’t need to use your custom CSS build for long.

Related posts:

  1. Using Google’s CDN for WordPress JavaScript
  2. Using jQuery in your WordPress plugins
  3. WordPress: Adding a Proper Visual Editor to Your Plugin

HTMLCenter Web Development Blog

Announcement: Winners of Deals2Have Giveaway

Sunday, February 12th, 2012

Advertise here with BSA

Announcement: Winners of Deals2Have Giveaway

We recently ran an excellent giveaway of 5 free Deals from Deals2Have (a site providing great discounts on digital products for Mac enthusiasts, creative professionals and startups). This post announces the 5 lucky Six Revisions winners who’ve won.

The Winners

Here are the winners of the Deals2Have giveaway:

Congratulations to all the winners! The winners should’ve already received information from the folks at Deals2Have on how to claim their prize via email.

About Deals2Have

Deals2Have, which started in summer of 2011, is a site where you can find big discounts on useful digital products.

For the latest deals and news, follow Deals2Have on Twitter, join them on Facebook and subscribe to their RSS feed.

Related Content

About the Author

Jacob Gube is the Founder and Chief Editor of Six Revisions. He’s also a web developer/designer who specializes in front-end development (JavaScript, HTML, CSS) and also a book author. If you’d like to connect with him, head on over to the contact page and follow him on Twitter: @sixrevisions.


Six Revisions

A Quick Lesson in WordPress Semantics

Sunday, February 12th, 2012

As much as I love WordPress, there are quite a few elements and functions in the system that can be a bit confusing, and even ambiguous. In this article, I’m going to try to explain and unravel a few of these items.

What’s the difference between the “home” page and the “front page”?

To many users, the terms “home” page and “front page” might seem like the same thing. However, in WordPress, they’re treated as two different elements. The “home” page is the main page that shows blog posts. If you install WordPress and don’t change any of the settings, this will be your site’s front page. However, if you modify the “Settings -> Reading -> Front page displays” setting to select “A static page (see below)”, and you choose a page for the “Front page” and a page for the “Posts page”, the “home” page is no longer the first page on your site. Instead, the first page on your site is the “front page”, now.

Therefore, when using the is_front_page() and is_home() conditional functions, you need to know what the distinction is.

The is_front_page() function returns true only when the visitor is viewing the static page you’ve set as your site’s front page. If you don’t have a static page set as your site’s front page, that function will never return true.

The is_home() function will return true on your site’s main blog page (the page that shows your latest blog posts).

What’s a “site”, a “network” or a “blog”?

Back when WordPressMU was a separate project from WordPress, the term “blog” was used to describe a single site within a WordPressMU installation and the term “site” was used to describe the collection of “blogs” (generally the entire MU installation).

When WordPressMU was merged into the WordPress core and became WordPress Multisite, the term “site” started to refer to single instances within a Multisite installation, and the term “network” began to refer to the collection of “sites”.

In the documentation and in the administration area, the terms “site” and “network” are used to describe these items, but, mostly for backwards-compatibility reasons, the terms “blog” and “site” are still used in the code itself.

Therefore, if you want to retrieve an option from a specific site in the installation, you use the get_blog_option() function; and if you want to retrieve a setting that applies to the entire network, you use the get_site_option() function.

There are a few exceptions to this one, as well, though. To figure out whether you’re viewing the administration area for the entire network, you use is_network_admin(). To add an admin notice that displays only in the network administration area, you hook into the network_admin_notices action. To add a new menu or submenu in the network administration area, you hook into the network_admin_menu action.

Is You Is, or Is You Ain’t My Baby?

A fairly consistent naming convention in WordPress applies to the conditional functions that report which page is currently being viewed. Most of these functions start with “is_”, followed by the type of page for which you’re testing. If you want to know if you’re currently viewing an archive page, you use is_archive(); if you want to know if you’re viewing a page, you use is_page(); etc.

There is one notable gotcha in WordPress Multisite, though. The function is_super_admin() isn’t a conditional tag used to test which page is being viewed; instead it tells you whether or not the user with the ID you supply is a Super Admin user.

Template Function Naming Convention

For the most part, there are two different versions of each template function in WordPress. One of those functions will normally start with “the_” while the other will start with “get_the_”. The “the” function will output (echo) the information into the page directly where you call it, while the “get” function will return the information so you can store it in a variable.

Some examples include:

  • the_content() & get_the_content()
  • the_title() & get_the_title()
  • the_post_thumbnail() & get_the_post_thumbnail()
  • the_excerpt() & get_the_excerpt()
  • the_category() & get_the_category()
  • the_tags() & get_the_tags()
  • the_date() & get_the_date()
  • the_time() & get_the_time()

There are a few exceptions where things differ slightly from this convention, though. For instance, if you want to echo the URL to a page/post, you would use the_permalink(); but if you just want to retrieve it, you use get_permalink() instead of get_the_permalink().

If you want to retrieve information about the site, or you want to retrieve various URLs related to the site, most of those functions don’t include the word “the” in them. The retrieval functions still start with “get_”, though. For instance, you would use get_bloginfo() to retrieve information about the site, but you just use bloginfo() to echo it.

Templates, Themes and Stylesheets

In WordPress, the word “theme” generally refers to any package of files that governs the appearance of the site.

The word “template” is a little more ambiguous. In most of the documentation and in the administration area, the word “template” refers to a specific file that you can apply to specific pages.

The term “stylesheet” in WordPress refers to the location of the chosen theme, while the term “template” can refer to the chosen theme (in the case of an independent theme), or it can refer to the parent theme on which the chosen theme depends.

If you are using a child theme, using bloginfo( ‘stylesheet_directory’ ) will echo the URL to the directory in which your child theme resides, while bloginfo( ‘template_directory’ ) will echo the URL to the directory in which the parent theme resides. If you’re using an independent theme, both calls will echo the same URL.

To make things even more fun, you can define the WP_DEFAULT_THEME constant, but it can only be used to set independent or parent themes as your default active theme. If you try to set a child theme as your default, you’ll end up with some PHP errors and warnings.

Paths, Directories and URLs

As if the template/themes/stylesheets thing wasn’t confusing enough; this is where it starts to get really confusing. For the most part, the word “path” describes the absolute system path to something, directory refers to the URL to the base directory in which a file resides and url refers to the actual URL to a file.

However, there are a lot of exceptions in WordPress to this nomenclature. In the bloginfo() and get_bloginfo() functions, template_url and template_directory both return exactly the same information (the URL to the base directory for the chosen theme).

Some constants, such as WP_CONTENT_DIR, WP_PLUGIN_DIR, WPMU_PLUGIN_DIR, etc., refer to an absolute system path; while others that use “dir”, such as PLUGINDIR and MUPLUGINDIR (both left in the code strictly for backwards-compatibility) refer to relative paths.

Then, there are constants that include the word “path” that refer to absolute paths (as you’d expect), such as TEMPLATEPATH (which actually refers to a “theme” rather than a “template”) and STYLESHEETPATH; but the related functions that are actually used to populate those constants use the word “directory” (get_template_directory() and get_stylesheet_directory()).

Related posts:

  1. WordPress Security Tip – Change Your Theme Name
  2. Using Javascript in WordPress Themes
  3. Get Information About Top-Level Pages in WordPress

HTMLCenter Web Development Blog

Zeus and WordPress Part 3: SSL Issues

Saturday, February 4th, 2012

While working to get WordPress functioning properly on a Zeus Web server, one of the issues I came across was the fact that I couldn’t seem to get any SSL functions working properly. I tried 2 or 3 different plugins, and all of them started causing infinite redirect loops as soon as they were activated.

Eventually, after quite a bit of investigating and testing, I found the cause of the issue: that particular server (and, presumably, all Zeus servers) doesn’t use any of the same indicators that SSL is being used that apache does. On apache servers, PHP usually has a handful of indicators that SSL is currently being used to serve the page. For instance, there’s a server global variable called “HTTPS” that gets set to “on” for many PHP configurations; SSL is generally served over port 443 instead of port 80; etc.

The WordPress HTTPS plugin runs four different checks to see if SSL is running, but all of them fail on Zeus. Following is the check that WordPress HTTPS runs:

public function is_ssl() {
    $https_url = parse_url($this->https_url);
    // Some extra checks for proxies and Shared SSL
    if ( is_ssl() && strpos($_SERVER['HTTP_HOST'], $https_url['host']) === false && $_SERVER['SERVER_ADDR'] != $_SERVER['HTTP_HOST'] ) {
        return false;
    } else if ( isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https' ) {
        return true;
    } else if ( $this->diff_host && !is_ssl() && isset($_SERVER['HTTP_X_FORWARDED_SERVER']) && strpos($this->https_url, 'https://' . $_SERVER['HTTP_X_FORWARDED_SERVER']) !== false ) {
        return true;
    } else if ( $this->diff_host && !is_ssl() && strpos($_SERVER['HTTP_HOST'], $https_url['host']) !== false && (!$this->ssl_port || $_SERVER['SERVER_PORT'] == $this->ssl_port) && (isset($https_url['path']) && !$https_url['path'] || strpos($_SERVER['REQUEST_URI'], $https_url['path']) !== false) ) {
        return true;
    }
    return is_ssl();
}

Like I said, at least on the Zeus server I was dealing with, all four of those checks failed, so it kept reporting that the page wasn’t running over SSL, so it caused an infinite redirect loop.

After a while, I did find a variable (actually, 3 of them) that, while it doesn’t seem to have any consistent value, always seems to be set when running SSL, and never seems to exist when running without SSL. That variable is the $_SERVER['HTTP_SSLCLIENTCERTSTATUS'] variable. Checking for the existence of that variable seems to consistently report whether or not SSL is running for the page.

For my purposes, I ended up editing a plugin called WPSSL (simply because it was simpler than making sure I’d edited all of the correct places within WordPress HTTPS) to check the existence of that variable.

Have you come across this same issue on a Zeus server? Is this common, or is this an issue unique to the particular host that’s being used for this project?

Related posts:

  1. Zeus and WordPress Part 2: Fixing Query Strings
  2. WordPress and Zeus Part 1: Getting Permalinks Working
  3. Programming your own PHP framework Part 2 – MVC

HTMLCenter Web Development Blog

Zeus and WordPress Part 2: Fixing Query Strings

Saturday, January 28th, 2012

If you’re trying to get WordPress working on a Zeus Web server, and you’ve gotten as far as using a good rewrite script to make permalinks work properly, you might have noticed that query strings don’t work at the ends of your permalinks. At first, it seemed like this wouldn’t be too big of an issue; it just meant that users wouldn’t be able to preview posts/pages, and there would be one or two other issues they’d have to live with. However, after using the site that way for a little while, we started coming across more and more issues that this caused, and it finally reached a tipping point.

To solve the issue, I wrote a simple function that runs any time a 404 error occurs on the site. Essentially, it parses the path of the requested page, cuts off the query string temporarily, and then searches the database for a post or page that has the slug at the end of the path.

You may be wondering why I didn’t just parse the request/get variables sent with the page. The problem is, those were empty in each of the cases I tested.

Anyway, following is the function I ended up writing.

function zeus_reply_fix() {
	if ( ! isset( $_SERVER['PATH_INFO'] ) ) {
		return;
	}
	if ( ! is_404() ) {
		return;
	}

	$path = $_SERVER['PATH_INFO'];
	$parts = explode( '/', $path );
	$qs = array_pop( $parts );
	$parsed = array();
	if ( strstr( $qs, '&' ) || strstr( $qs, '?' ) ) {
		parse_str( $qs, $parsed );
	} else {
		return;
	}
	if ( is_array( $parsed ) ) {
		global $wpdb, $post, $wp_query;
		$post_ID = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM {$wpdb->posts} WHERE post_name=%s", array_pop( $parts ) ) );

		if ( empty( $post_ID ) ) {
			return;
		}

		$wp_query = new WP_Query( array( 'page_id' => $post_ID ) );
		$wp_query->is_404 = false;
		foreach ( $parsed as $k=>$v ) {
			if ( ! empty( $k ) && ! empty( $v ) )
				set_query_var( $k, $v );
		}

		$_GET = $_GET + $parsed;

		$use_template = 'index.php';
		$post = $wp_query->get_queried_object();

		load_template( trailingslashit( get_template_directory() ) . $use_template );
		die();
	}
}
add_action( 'wp', 'zeus_reply_fix', 99 );

Have you found a better way of dealing with this issue? Do you see anything that could be done better? I’d love to see other solutions to this particular problem with Zeus & WordPress.

Related posts:

  1. WordPress and Zeus Part 1: Getting Permalinks Working
  2. WordPress Multi-Site: Get Featured Image from Another Blog
  3. Order WordPress Pages By Multiple Fields

HTMLCenter Web Development Blog

Giveaway: 100 Custom Flyers from Next Day Flyers

Monday, January 23rd, 2012

Advertise here with BSA

Click here to open Next Day Flyers - Club Flyers page in a new browser tab/browser window.

We’ve partnered up again with our wonderful friends at Next Day Flyers to give away two sets of 1/4-page flyers with free shipping anywhere in the Continental U.S. Each set contains 100 flyers. Flyer printing can be used and customized for a variety of purposes including promoting a club event, marketing a small business and sending out announcements. Read on to see how you can win!

About Next Day Flyers

Next Day Flyers is an offset printing company offering an array of printed materials such as flyers, business cards, postcards, brochures, tickets and more.

They’re not newcomers to the industry. They’ve been in business for 13 years and have over 100,000 satisfied customers.

And with longevity comes experience. They know what their customers are seeking and how to meet the high expectations.

Quality is of utmost importance as Next Day Flyers utilizes a quality checkpoint system which includes 33 steps to ensure the files are printed correctly and ready on time.

And speaking of time, this is a strong point of Next Day Flyers. As the name suggests, they offer next day turnaround time, but as customers asked for a same-day print option, that was added too. So files in by 10:00 AM PST can be printed the same day, while files in by 6:00 PM PST can be printed and ready to pick up or ship the next day.

The Next Day Flyers online ordering system allows for easy file uploads of print ready files. They have file prep guides and templates available to make sure the bleeds, size, color are set to print correctly.

How to Win

To win, simply answer the following question:

  • How can these flyers help you and/or your business?

Giveaway Details

This giveaway ends on Monday, January 30, 2012 after which the comments section on this post will be closed and you will no longer be able to leave a comment. Shipping outside of the continental U.S. will incur extra costs. Please leave a valid email address when filling out the comment form so that we can contact you if you have won. Please only comment once. The winners will be randomly selected using a similar method as previous Six Revisions giveaways. The winners will be announced on a separate post. You are advised to subscribe to our RSS feed so that you can be quickly notified when the winners announcement post has been published. Please note that comments are moderated and so your comment may not show up right away. Please note that comments that do not follow the instructions on how to win (described above) may not be published, or may be removed later on.

Related Content

About the Author

Jacob Gube is the Founder and Chief Editor of Six Revisions. He’s also a web developer/designer who specializes in front-end development (JavaScript, HTML, CSS) and also a book author. If you’d like to connect with him, head on over to the contact page and follow him on Twitter: @sixrevisions.


Six Revisions

WordPress and Zeus Part 1: Getting Permalinks Working

Saturday, January 21st, 2012

For those of you that might not know (and I was one of you about a month ago), Zeus is a Web server package that’s used instead of apache by some Web hosts. If you’re planning to use WordPress, and you have a choice between apache and Zeus, I would definitely recommend choosing apache. However, sometimes you don’t have a choice in the matter; and you have to do what you can to make things work.

WordPress will work out of the box with Zeus, but a lot of things won’t behave the way you might expect. One of those things is the permalink structure.

Instead of getting nice, clean URLs like “http://example.com/blog/2012/01/my-first-blog-post/”, you get “index.php” shoved in there (like “http://example.com/index.php/blog/2012/01/my-first-blog-post/”). You can correct this issue, but it’s not quite as simple as updating an .htaccess file (in fact, without some jiggery-pokery by your Web host, Zeus doesn’t support .htaccess at all). Instead, you have to apply a rewrite script to your server configuration.

After quite a bit of searching and trial & error, I finally found a working rewrite script configuration for WordPress. A hosting company called ZipHosting posted the scripts below in their knowledgebase. The first script is set up for you to use if WordPress is hosted in a subdirectory, and the second is for use with WordPress in the root directory.

WordPress in a Subdirectory

RULE_0_START:
    # Get the document root path and put value into the SCRATCH array.
    # This is the server path not the web URL.
    # i.e. /clientdata/clients/p/h/php.testing.au.com/www/

map path into SCRATCH:DOCROOT from /

    # Get the URL without the domain.
    # e.g. /test&colour=red
    # e.g. /an-example-post/?color=red

 set SCRATCH:ORIG_URL = %{URL}
 set SCRATCH:REQUEST_URI = %{URL}

    # See if there are any queries in our URL.

 match URL into $ with ^(.*)\?(.*)$

    # If there are...

 if matched then
    # Set a var to path without the domain part.
    # e.g. /an-example-post

     set SCRATCH:REQUEST_URI = 

    # Set a var to the passed queries.
    # e.g. colour=red

     set SCRATCH:QUERY_STRING =
 endif
 RULE_0_END:

RULE_1_START:
    # This is setting a var to the server path and sub folders.
    # e.g. /clientdata/clients/p/h/php.testing.au.com/www/wordpress/an-example-post/

 set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
 set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}

    # Check to see if the file exists.

 look for file at %{SCRATCH:REQUEST_FILENAME}
 if not exists then

    # The file wasn't found so is it a folder?

     look for dir at %{SCRATCH:REQUEST_FILENAME}
     if not exists then

    # No folder either. So now check the URL for special hosting folders.

         match SCRATCH:ORIG_URL into % with ^/stats|^/logs
         if matched then

    # If a special folder was requested end the script.

             goto END
         else

    # There were no files, folders or special folders so set the new URL.
    # -- Sub directory -------------------------------------------------------------
    # If the blog is in a sub directory...replace the words in bold  with your directory name.
    # e.g. /wordpress/index.php/an-example-post

             match SCRATCH:REQUEST_URI into $ with ^/wordpress(.*)
             if matched then
                 set URL = /wordpress/index.php
             endif

    # -- Sub directory ends --------------------------------------------------------
    # or...
    # -- Top level -----------------------------------------------------------------
    # If the blog is in the top level of the site...
    # e.g. /index.php/an-example-post
    # set URL = /index.php%{SCRATCH:REQUEST_URI}
    # -- Top level ends ------------------------------------------------------------
    # Go to the next rule.

             goto RULE_2_START
         endif
     endif
 endif

    # If files or folders were found end the rewrite script.

 goto END
 RULE_1_END:

RULE_2_START:

    # Check for queries in the requested URL.

 match SCRATCH:ORIG_URL into % with \?(.*)$
 if matched then

    # If queries were found add them to the new URL.
    # e.g. /index.php/an-example-post/&colour=red

     set URL = %{URL}&%{SCRATCH:QUERY_STRING}

 endif

    # -- Sub directory -------------------------------------------------------------
    # If you only want to rewrite the sub directory uncomment this bit.
      match SCRATCH:ORIG_URL into % with ^/wordpress
 if matched then
    # -- Sub directory ends --------------------------------------------------------

    # End the script.

     goto END

    # -- Sub directory -------------------------------------------------------------
 endif
    # -- Sub directory ends --------------------------------------------------------
 RULE_2_END:

WordPress Installed in the Root Directory

RULE_0_START:
    # Get the document root path and put value into the SCRATCH array.
    # This is the server path not the web URL.
    # i.e. /clientdata/clients/p/h/php.testing.au.com/www/

map path into SCRATCH:DOCROOT from /

    # Get the URL without the domain.
    # e.g. /test&colour=red
    # e.g. /an-example-post/?color=red

 set SCRATCH:ORIG_URL = %{URL}
 set SCRATCH:REQUEST_URI = %{URL}

    # See if there are any queries in our URL.

 match URL into $ with ^(.*)\?(.*)$

    # If there are...

 if matched then
    # Set a var to path without the domain part.
    # e.g. /an-example-post

     set SCRATCH:REQUEST_URI = 

    # Set a var to the passed queries.
    # e.g. colour=red

     set SCRATCH:QUERY_STRING =
 endif
 RULE_0_END:

RULE_1_START:
    # This is setting a var to the server path and sub folders.
    # e.g. /clientdata/clients/p/h/php.testing.au.com/www/wordpress/an-example-post/

 set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
 set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}

    # Check to see if the file exists.

 look for file at %{SCRATCH:REQUEST_FILENAME}
 if not exists then

    # The file wasn't found so is it a folder?

     look for dir at %{SCRATCH:REQUEST_FILENAME}
     if not exists then

    # No folder either. So now check the URL for special hosting folders.

         match SCRATCH:ORIG_URL into % with ^/stats|^/logs
         if matched then

    # If a special folder was requested end the script.

             goto END
         else

    # There were no files, folders or special folders so set the new URL.
    # -- Sub directory -------------------------------------------------------------
    # If the blog is in a sub directory...replace the words in bold  with your directory name.
    # e.g. /wordpress/index.php/an-example-post

    # match SCRATCH:REQUEST_URI into $ with ^/wordpress(.*)
    # if matched then
    #     set URL = /wordpress/index.php
    # endif

    # -- Sub directory ends --------------------------------------------------------
    # or...
    # -- Top level -----------------------------------------------------------------
    # If the blog is in the top level of the site...
    # e.g. /index.php/an-example-post
     set URL = /index.php%{SCRATCH:REQUEST_URI}
    # -- Top level ends ------------------------------------------------------------
    # Go to the next rule.

             goto RULE_2_START
         endif
     endif
 endif

    # If files or folders were found end the rewrite script.

 goto END
 RULE_1_END:

RULE_2_START:

    # Check for queries in the requested URL.

 match SCRATCH:ORIG_URL into % with \?(.*)$
 if matched then

    # If queries were found add them to the new URL.
    # e.g. /index.php/an-example-post/&colour=red

     set URL = %{URL}&%{SCRATCH:QUERY_STRING}

 endif

    # -- Sub directory -------------------------------------------------------------
     # If you only want to rewrite the sub directory uncomment this bit.
    # match SCRATCH:ORIG_URL into % with ^/wordpress
 if matched then
    # -- Sub directory ends --------------------------------------------------------

    # End the script.

     goto END

    # -- Sub directory -------------------------------------------------------------
 endif
    # -- Sub directory ends --------------------------------------------------------
 RULE_2_END:

Unfortunately, that won’t solve all of your permalink issues, but it will get you started. One serious issue you might encounter is the fact that query strings aren’t recognized at the end of your permalinks; instead, WordPress shows a 404 error page whenever a query string is attached. In my next article, I’ll explain how I fixed that issue.

Related posts:

  1. WordPress: Creating Custom Permalinks for Plug-Ins
  2. Installing WordPress Through SSH
  3. My First Official WordPress Plugin

HTMLCenter Web Development Blog