“Windows 8 is too hard to turn off”

Did you know the Windows 8 operating system is too hard to shut down? In fact, it’s a “pain-in-the-rump,” according to¬†Steven J. Vaughan-Nichols of ZDNet.com.

I must be honest – when I read those words I just thought to myself, this guy cannot be serious. The gentleman is a technically-savvy author, writing for ZDNet, coming from a background that is replete with relevant experience, and he thinks Windows 8 is too hard to shut down?

In Windows 8, the shutdown button is literally one click from the desktop, or one simple command: WinKey+I. As a Linux user, I would expect Steven to appreciate the brevity of keyboard shortcuts, but in his defense he may not have even known about this shortcut. The other method is simply to navigate to the top-right of your primary screen to reveal the charms, then click the “Settings” icon. (See: Getting around in Windows 8)

While I completely dismiss Steven’s worries about Windows 8 (having used it myself as my primary OS since the developer preview), I do admit that his tone and message could have come across a lot worse. In the end, I think Steven’s article is just a Linux user upset that Windows 8 isn’t Linux – and I don’t mean that in some snarky disrespectful way. We all have our likes and dislikes; he likes Linux, I like usability (okay, that was a bit snarky, hehe).

While I had to fight back the urge to jam pencils into my eye-sockets reading his complaint, I just remind myself, it could have been a lot worse.

First Impression of Windows 8 (Developer Preview)

I downloaded the developer preview of Windows 8 a few weeks ago so that I could begin playing with Internet Explorer 10. After setting up a new partition and loading the OS into a dual-boot environment, I was quickly up and running in Windows 8. I’ve been using the operating system almost exclusively now for a while, and I wanted to share some of the things I like, and some of the things I don’t like so much. In complete honesty, the likes greatly outweigh the dislikes – in fact, the dislikes are probably too few to require more than half a hand to list (but of course that may grow with more exposure and experience).

I write this today as somebody who knows nothing about what specific goals Microsoft has in developing this operating system. All I know is that it’s something of a one-size-fits-all, in that it’s intended to be used on both the desktop, as well as the mobile tablet interface. I’ll be honest, that fact alone had me a little suspicious. My desktop and my tablet are two radically different experiences. But could Microsoft really pull it off, and create something for both?

Fast, So Fast!

Setting up windows was quick and required very little effort. One thing I thought was especially interesting was the prompt I received to give the Setup Wizard my Live account email address. My user account is directly tied to my Live account, which I thought was pretty cool.

As cool as the Live account integration was, that wasn’t what floored me during setup: the actual boot time was! From the boot screen to my login screen, the process of getting into the OS often takes less than a few seconds. Honestly, when I select the Windows 8 Developer Preview from my boot screen, I find it difficult to actually count more than 2 seconds or so – what a joy it is to not sit and wait.

Here’s another demo online from Microsoft themselves, though I think my PC loads up just a bit faster – but hey, it’s no contest, right? ūüôā

Of course the boot screen itself is pretty handsome now too – no more white text on a black background, Windows 8 is purdy!

Multiple Displays

I am running Windows 8 on a dual-monitor setup. This meant that when I log into the machine, my left (Primary) monitor loads up the new start screen, and my right monitor (secondary display) loads up a more traditional looking desktop.

This was the first major impression made – the interface for interacting with the computer had changed completely. While a little lost, and scared, I was excited. Scrolling up and down would slide all of these neat little panels left and right, revealing games, applications and other goodies. The first thing I did was jump into the Zero Gravity game and get lost in weightless-adventure for about an hour (I didn’t have my sound working at this point, so I’m¬†surprised¬†I managed to play that long without audio).

Gorgeous New Task Manager

After poking around on this screen for a bit, I clicked the “desktop” panel which slid the start screen out of the way to reveal a classic desktop experience on both monitors – ah, now I feel at home.

I was curious how much memory this OS uses, so I decided to visit the performance tab from the task-manager: CTRL+ALT+DEL brought up another nice screen, and sure enough, Task Manager was there on the list of items to select.

Immediately I noticed a much nicer looking task manager – good for him, he’s been pretty ugly for as long as I can remember.

I love how much details is shared in this newer task manager, and how nicely presented it is as well. The varying yellow background colors change as frequently as the values in the cells do themselves. It’s pretty neat – just a small panel of flashing cells and fluctuating numbers. Really puts you in that “I’m Neo, and I’ll bend your reality” state of mind. But this wasn’t what I wanted to see, I wanted to see the Performance tab.

Goodness, even more beauty! I love the colors, the layout, the entire experience is just awesome. I realize I probably sound like a Microsoft fan-boy at this point, but I don’t have an agenda here, my excitement is entirely organic. From one panel I can see my CPU usage, Memory usage, current Disk usage, Data sent and received over ethernet, as well as my current transfers in Kbps, and so much more. And to top it off, it’s actually aesthetically pleasing.

Okay, Time for a Complaint (Kinda)

I would hardly convince you that I’m being fair here if I didn’t list a few things that bother me about my initial experience with Windows 8 Developer Preview. Your Start button (or ‘Pearl’) is no more, it’s dead, it’s gone – write up its eulogy. Unfortunately, ¬†I don’t think that we have been given anything better in its place. In fact, we’re given a very confusing alternative.

Both of my displays have their own taskbar, and both also have their own start button. This wouldn’t be so bad if each of the start buttons didn’t behave differently. On my main display, hovering over the start button reveals a small fly-out menu, as well as a large over-sized date (which I actually like):

Careful, don’t click that button. Clicking it will throw you back into the start screen with the fancy panels. This is what I mean by the start button that we all know and love is dead. I instinctively click this thing about once a day it seems, especially when I’m trying to find something I just installed.

Meanwhile, over on display two, there’s an odd looking icon in the place of the start button:

This button, when clicked, actually swaps the two buttons. If you click this, the start button from the primary display will replace this, and this will occupy the old location of the primary start button. Confusing, eh?

Essentially this button moves your fancy-panel screen over to this display. Clicking this button on my secondary display causes the neat new home screen of panels to be revealed on this monitor as opposed to my primary monitor.

The complaint here is that the traditional start button that we have known for nearly all of Windows’ history is dead and gone.¬†Admittedly, it doesn’t take long to get used to this new¬†behavior, but it’s entirely unexpected. Additionally, you can’t just hover over any portion of the main start button to reveal the fly-up mini-menu. From what I can tell, you have to hover over the lower-left corner of the button. At times I’ve found myself hovering over the button while thinking to myself “What the eph, computer – respond!”

Finally, Smart Taskbars!

The taskbar has always been a frustrating thing for me. I’ve found myself wanting them to be a bit smarter for several iterations of the Windows operating system, and with Windows 8, Microsoft has delivered! One feature in particular really excited me.

So, a lot of this stuff is pretty standard, but the “Windows appear” portion is what caught my attention. To be honest, I didn’t really understand what it meant, “Unique to each taskbar,” so I selected it and applied. I immediately found out that any programs opened on my primary display would show up in my primary taskbar, and any programs opened on my secondary display would show up in my secondary taskbar.

Further, dragging a window from display 2 over to display 1 results in taskbar 2 giving up the application to taskbar 1. Awesome! No longer does my taskbar just tell me that I have a program opened, somewhere, but it is now smart enough to tell me which display contains which application.

This post is quickly becoming a bit too large, so I’ll cut it off here. The more I use the Developer Preview the more I’ll have to say about it. But so far, I’m very pleased with what I’ve been seeing. Nice work, Microsoft.

prependChild on DOMElement in PHP, Sort of.

This evening I wanted to add a new LI onto a WordPress navigation programmatically. After considering a few different options, I decided I wanted to use PHP’s DOMDocument, and use this as an opportunity to more familiarize myself with its ins and outs.

Looking into DOMElement, I was pleased to see there was an appendChild() method, but a little down to see there there was no prependChild(). After searching online, I saw a few people creating custom classes to make their way around this absense, however I found a method that I prefer a little more.

Stumbling upon insertBefore(), I realized all of my problems had been solved…kinda.¬†insertBefore() was leaving me just a bit confused; it sounds as though you call it from the element you wish to move around, but you don’t. In fact, you don’t even call it on the element you’re trying to snuggle up against. Instead, you call it on the parent of the two, referencing both elements as the arguments.

add_action( 'wp_nav_menu', 'custom_nav_menu' );
function custom_nav_menu( $menu ) {
  // Load it
  $html = new DOMDocument();
  $html->loadHTML( $menu );
  // Get it
  $list = $html->getElementsByTagName( 'ul' )->item( 0 );
  $first = $list->getElementsByTagName( 'li' )->item( 0 );
  $new_item = $html->createElement( 'li', 'Hello World' );
  // Place it
  $list->insertBefore( $new_item, $first );
  // Show it
  return $html->saveXML( $list->parentNode );
}

This gave the desired results, without requiring any new classes or other more complicated work-arounds. To my knowledge I don’t see any downfalls of it either, at least not at this time.

Some of you may be scratching your head at the last line, where I’m calling saveXML() rather than saveHTML(). As for 5.3.6 you can pass in an optional DOMNode to specify which portion of the DOMDocument you’d like to render. I happen to be using 5.3.5, so this option is not available to me and all I got to see was a nasty error message. Fortunately saveXML() worked as a nice substitute with little-to-no side-effects.

Sometimes jQuery is (not) the Answer

It’s difficult to say, as much as I love jQuery I must admit that it is at times the wrong route to take when addressing a problem.

While looking over a few questions on StackOverflow today I came across a poster who was seeking to modify the width of all nested elements within a container – he naturally thought jQuery would be a good, simple solution – and it is. But while it may be simple, it’s wrong in this case.

Rather than coming right out and answering with something like:

$("#container").find("*").width("100%");

I instead took just a moment to whip up a test case on http://jsperf.com (great site for testing the performance advantages of one method over others.) Just as I had suspected, jQuery would be slower than raw JavaScript – much, much slower.

var i,
    container = document.getElementById("container"),
    tags = container.getElementsByTagName("*"),
    total = tags.length;

for ( i = 0; i < total; i++ ) {
  tags[i].style.width = '100%';
}

This simple block does the same thing as the aforementioned jQuery code, but it’s much faster. In fact, in the time it takes the jQuery code to perform 20k operations, the raw JavaScript code performs nearly 300k!

You can see this particular performance test online at http://jsperf.com/resizing-children.

Todays WTF Moment with CodeIgniter, MySQL and PHP

As routine as an oddly-twitching finger sabotaging any attempt to use your mouse, strange things  may take place with your environment, tools, or code. Today I was working on setting up a very small project with CodeIgniter when I came across the task of establishing database credentials so I could auto-load my resources and have a fresh connection waiting on me hand and foot.

Opening up application/config/database.php I went ahead and placed my hostname, username, password, and database name. Almost done, right? Next I went to application/config/autoload.php and updated the $autoload[‘libraries’] array to include “database”. Done, right?

To my surprise I had a whole storm of agony just waiting on me to try and pull some results from my model. When I did just that…

This took me back just a moment – I had put in the right data, right? I’m working on “localhost”, and my db user is “root” with a blank password. How exactly do you screw that up? After double-checking, my credentials showed to be valid. So I went to make sure I was auto-loading the database properly; perhaps I said “datbase” instead of “database”? Who knows, it’s happened before. Nope, I had this value correct as well.

It’s around this moment Google must necessarily be opened and error messages must necessarily be pasted into the search bar. Anytime I have problems like these, which turn me to Google, I’m reminded at just how unreliable forums are. I inevitably ended up looking at about 12 different forums, where people can post whatever the flip they think might be the problem and you have very little reason to doubt them in your ignorance.

“Did you provide your port number?” “Did you update your hosts file to associate ‘localhost’ with 127.0.0.1?” “Did you max out your connections?” All of these where the types of questions being asked, and yet none of them did me any good. My host file is fine – I run plenty of websites. I’m not maxing out my connections either – I’m the only sap accessing the laptop! It wasn’t until I came across a PHP bug filed in 2008 regarding PHP 5.3’s inability to use MySQL functions when using “localhost”.

Now, this bug submission was eventually marked as “bogus,” but it wasn’t entirely useless because it got me to explore another route in my troubleshooting. Out of curiosity I looked down to my instance of WAMPServer to see what version of PHP I was running; 5.3.1.

Out of curiosity, I switched to 5.3.5. My server went offline, restarted, and was back up and running in just a matter of seconds. Time to try my CodeIgniter app again…Bingo!

The connection issues were resolved by switching from 5.3.1 to 5.3.5. Just for some environmental facts and info, I’m running WAMPServer 2.0, Apache 2.2.11, MySQL 5.1.33 and PHP 5.3.1 (Well, 5.3.5 now). The CodeIgniter version is 2.0.2.

At this point, I still have no idea what causes this problem but I am sure glad it’s done with so I can get back to work. If you’re having a similar problem, on a similar setup, perhaps this will help you as well.

If anybody knows what actually causes this problem, I’d love to know in the comments below.

Unexpected Results While Styling WordPress Menus

Today I sat down to convert a static theme consisting of nothing more than HTML and CSS into a WordPress theme, complete with calls to functions like wp_nav_menu() for the construction of the menu’s. For this particular theme I began with a copy of the TwentyTen theme. When I came across the task of establishing a navigational menu I found some rather unexpected results from WordPress – something I think they should consider changing in future releases. (Note: The following assumes version 3.1.3 is being used)

When you open up header.php in the TwentyTen theme you’ll find the following on or around line 85:

<?php wp_nav_menu( array( 
  'container_class' => 'menu-header', 
  'theme_location' => 'primary' 
) ); ?>

This is really pretty straight forward. It defines itself as the location for any menu assigned to the “primary” spot. Additionally, it sets a container class to “menu-header”. Given this information, we should expect this to result in is an unordered list wrapped in a div (the default container is a div) that has the class “menu-header”. So what markup is generated by WordPress when somebody sets up a fresh copy of it and checks out their TwentyTen theme?

<div class="menu">
  <ul>
    <!-- ... -->
  </ul>
</div>

At first there may not appear to be any problems, but look more closely at the container class declared in the call to wp_nav_menu() and what is actually applied in the generated markup. While we declared a class of “menu-header”, what we actually get is a class of “menu”. This really frustrated me this evening.

Some users of WordPress have been unable to reproduce this effect, and the reason is fairly simple why they couldn’t – they likely have a menu already assigned to the “primary” location. Anybody who does not initially have a menu created and applied to this location will be left scratching their head.

So what is WordPress doing exactly? Initially WordPress will look for a menu assigned to this location, if it doesn’t find one it will move on to do something else. Along down the line, just before throwing its hands up completely it will call a fallback method to generate something for the user. The default fallback method is provided for us in the source (line 141):

$defaults = array( 
  /* ... */
  'fallback_cb' => 'wp_page_menu'
  /* ... */
);

So if no menu is present when wp_nav_menu() is called, it will fallback into calling the wp_page_menu() method. Up to this point this shouldn’t seem like much of a threat. Sure, if I don’t have a menu WordPress can go ahead and generate a list of pages that I might have published. Unfortunately, this is where some communication-breakdown occurs and things get a bit messy.

Recall the generated HTML list previously shown, this is what wp_page_menu() generated for us in the absence of a user-defined menu. Like wp_nav_menu(), wp_page_menu() has its own set of internally-declared default arguments that will determine much of how the results will look and feel. We can see these defaults declared below:

$defaults = array(
  'sort_column' => 'menu_order, post_title', 
  'menu_class' => 'menu', 
  'echo' => true, 
  'link_before' => '', 
  'link_after' => ''
);

The only thing we’re interested in right now is the ‘menu_class’ which, by default, is set to “menu”. This is where the “menu” class comes from in the place of our “menu-header” class passed to wp_nav_menu(). This isn’t the light at the end of the tunnel, things get even messier from here.

While it’s nice of WordPress to generate a list for us in the absence of a menu, the integrity of our data breaks down in the process. When we call wp_nav_menu() and tell it to set the “container_class” to “menu-header”, the resulting call to wp_page_menu() completely ignores this request. Again, this isn’t the end of the mess, the wp_nav_menu() function also allows us to provide a ‘menu_class’, or a class which should be applied to the generated menu within the container. Suppose we did this:

<?php wp_nav_menu( array( 
  'container_class' => 'menu-header', 
  'menu_class' => 'foo', 
  'theme_location' => 'primary' 
) ); ?>

What we should expect to see from this is a menu that looks like the following:

<div class="menu-header">
  <ul class="foo">
    <!-- ... -->
  </ul>
</div>

This should be the result regardless if pages or custom menu items populate the UL. If no menu is present, and WordPress falls back on the wp_page_menu() function, what it generates is anything but expected:

<div class="foo">
  <ul>
    <!-- ... -->
  </ul>
</div>

Note how the “menu_class” is actually applied to the container, and the “container_class” of “menu-header” is entirely abandoned. This isn’t what we asked for.

If we turn around and create a menu called “Sample Menu”, and set it to be displayed in the “primary” location, what we are presented with is the following:

<div class="menu-header">
  <ul id="menu-sample-menu" class="foo">
    <!-- ... -->
  </ul>
</div>

Notice how it gets the container class correct, and the menu class correct when we actually have a menu for it to display.

I’m hoping this problem will be resolved in future versions of WordPress for the sanity of those creating themes. Not for them alone, but for the reputation of WordPress as a whole too. If its own internal communication isn’t consistent, it makes for a very bad testimony when those of us out in the real world are attempting to act as evangelists for the wonderful platform.

Using Views in Kohana 3

What is a View?

If you’ve never worked with Kohana Views in the past, they’re not hard to understand. Controllers handle most of your logic, Models handle the database communication, and Views handle the presentation of the data (generally-speaking). In Kohana, views are very easy to work with. Unfortunately, a fresh install of Kohana won’t contain a default view for you so we’ll have to make one ourselves. I trust you’ve installed and configured Kohana 3 on your server and are ready for what follows.

Adding our first View

Stepping back a moment, by default Kohana’s example controller sends text directly to the output without loading a view – perhaps you’ll find cases where this is desirable (especially when debugging), but for the most part it’s not what you’ll want to be doing. When developing your next project, you’ll want to build views that represent templates, modules, and many other aspects of your design.

Suppose we have the following saved to application/views/myview.php

<p>If you see me, the view loaded.</p>

This is nothing more than a paragraph element and some static text, but let’s load it from within a controller. I should mention that there are a couple different ways you can load a view, but they’re all pretty straight forward and intuitive.

Loading our View

class Controller_Demo extends Controller {
  public function action_index()
  {
    $this->request->response = View::factory( 'myview' );
  }
}

In this case we’re using the static factory method of the View class to load the view file we previously created. Note also that I’m not providing the .php extension – Kohana figures that out for itself. If myview.php was in a subfolder, we would reflect that in the path passed to the factory method.

Kohana 3 is loaded onto my localhost, so visiting http://localhost/kohana/demo/index results in showing me the contents of my view, meaning the view was loaded properly. If your view isn’t loading properly, make sure you placed it within application/views, and that your controller code contains no mistakes.

Handling a View from a variable

Another way to load a view is to place it within a variable reference, and then pass that into the response.

class Controller_Demo extends Controller {
  public function action_index()
  {
    $view = View::factory( 'myview' );
    $this->request->response = $view->render();
  }
}

With time you’ll settle on the method you prefer most. In fact, what we’re about to cover might help determine which method you prefer most.

Passing Data to your View

Views are not necessarily restricted to being static files – they wouldn’t be all that useful if they were. Controllers can pass variables into views to be displayed upon pages. Let’s go back to our view from above and change our static text to something a bit more dynamic and open to more possibilities:

<p><?php echo $message; ?></p>

Here our view is expecting to display the $message variable, so we have to be sure to provide this value within our controller. Passing variables and values into views is also a task that can be done a couple different ways. One very common method is to create an associative array, and pass that into the static factory method:

class Controller_Demo extends Controller {
  public function action_index()
  {
    $data['message'] = "Hello, World";
    $this->request->response = View::factory( 'myview', $data );
  }
}

What this does is makes all $data array keys available within the view as variables themselves, so $data[‘message’] within the view is $message. Refreshing your page should result in a new message, “Hello, World”.

Adding Data via the Set Method

The view class also contains many method to allow the adding data on a variable-by-variable basis. We can use the set method to add a variable to a view as well.

class Controller_Demo extends Controller {
  public function action_index()
  {
    $this->request->response = View::factory( 'myview' )
      ->set( 'message', 'Hello, World' );
  }
}

The set method of the view class accepts two parameters: 1) The key, and 2) the value. Like the previous method, this also creates a variable called $message within the view with whatever value you provide. The set method also allows you to add an array of values:

class Controller_Demo extends Controller {
  public function action_index()
  {
    $this->request->response = View::factory( 'myview' )
      ->set( array( 'Name' => 'Jonathan', 'Year' => 2011 ) );
  }
}

When you provide an array, the set method will cycle through your array and add all of your values as if you had done each one of them individually with the previous style of using the set method.

Chaining the Set Method

Another thing to note about the set method is that it’s chainable, meaning you can run it over and over and over again.

class Controller_Demo extends Controller {
  public function action_index()
  {
    $this->request->response = View::factory( 'myview' )
      ->set( 'name', 'Jonathan' )
      ->set( 'year', '2011' )
      ->set( 'website', 'http://sampsonresume.com' );
  }
}

Working directly with the View

So far we’ve been using the set method in conjunction with the static factory method, but you can do the same thing even if you apply the view to a variable earlier in the control:

class Controller_Demo extends Controller {
  public function action_index()
  {
    $view = View::factory('myview');
    $view->set( 'name', 'Jonathan' );
    $this->request->response = $view->render();
  }
}

Another method of adding data is to just add it directly to the view object itself:

class Controller_Demo extends Controller {
  public function action_index()
  {
    $view = View::factory('myview');
    $view->message = "Hello, World";
    $this->request->response = $view->render();
  }
}

Setting Global Variables

At times you may want to make a variable available to all views that are loaded. The view class makes this easy as well via its global data array.

class Controller_Demo extends Controller {
  public function action_index()
  {
    View::set_global('message', 'Hello World');
    $this->request->response = View::factory('myview')
      ->set( 'myWidget', View::factory('anotherview') );
  }
}

In this example you can see that we call the set_global method early in the controller logic. The variable $message will now be available in all views loaded. You can also see that I’ve loaded a second view into the first, and represented it with the variable $myWidget. Both views can reliably access the global $message variable now.

There’s still a lot more you can do with views, like passing variables by reference via the bind method. The bind method is just like the set method, with the one caveat that the variable is being passed by reference and isn’t being copied:

class Controller_Demo extends Controller {
  public function action_index()
  {
    $view = View::factory( 'myview' );
    $myVal = "Hello, World";
    $view->bind( 'message', $myVal );
    $this->request->response = $view;
  }
}

In this example $myVal is being assigned by reference to $view->message. If the value of $myVal changes, this change will reflect automatically within $view->message since the value is assigned by reference via the bind method. You can also use the bind_global method if you need set_global functionality while maintaining references.

Jeff Atwood on The Pipeline

Like many people, I listen to podcasts most of the time I’m writing code. Unfortunately, most of these podcasts don’t have large financial backing and so at times they will dwindle up and die whilst others are sprouting up to take their place – keeps you on your feet.

Such was the case with one of my favorite podcasts, the StackOverflow Podcast, which nearly reached 90 episodes before shriveling up and dying in April of 2010 (tentatively speaking…could just be on a very long hiatus!). Fortunately, Jeff Atwood (from Coding Horror) still makes his rounds onto other podcasts.

One of Atwood’s latest interviews took place on 5by5‘s show The Pipeline. Head over and listen to the discussion about Jeff’s beginnings up to his present fame with the programmer’s paradise¬†StackOverflow. For convenience, I’ve also placed the audio below.

[audio:http://5by5.tv/d/a/2010/5/183/pipeline-038.mp3]

“Jeff Atwood talks with Dan Benjamin about starting a business, running projects, software development, StackOverflow, and more.”

Finding and Linking to Adjacent Posts with Same Custom Key/Value Pair in WordPress

Today I continued working on merging multiple custom post types back into regular posts, and differentiated them with a custom key/value pair. Some of these old post types would link to their adjacent siblings – videos to previous and next videos, cartoons to previous and next cartoons, etc. With these posts no longer being a custom post type, a video would be linking to whatever post preceded it, which would be an article, cartoon, or any number of things – this wasn’t good.

I wasn’t thinking this would be too much of an issue, after all, don’t we have the freedom to provide constraints to functions like previous_post_link() and can’t we tell functions like get_posts() to return only posts whose ID is greater than or less than the current post id? I was wrong on both assumptions – kinda. You do have the freedom to create some constraints on previous_post_link(), but only at the category level. That means if I wanted videos to only link to videos, I would have to use category names as some form of post type¬†declaration, and I’m not about to do that. As for get_posts(), you cannot use any less-than or greater-than logic in relation to the present post ID.

What now? The solution I ended up going with was found in filters, specifically a custom filter tied to the “posts_where” filter. This idea comes from the WordPress documentation on the query_posts() function which provides an example of how to get posts whose date is within a timespan.

So the filter I ended up creating looks like this:

function filter_where_prev( $where = '' ) {
  global $post;
  return $where .= " AND ID < " . $post->ID;
}

I should note that that this code does in fact reside within single.php. The post id used will be from whatever post is presently residing in the $post variable. Next, we add this filter onto WordPress’ native filter. We’ll do this via the add_filter() function.

add_filter( "posts_where", "filter_where_prev" );

At this point we can now leverage the inherent power of the query_posts() function to tie things up. Remember that I wanted to restrict my results to posts that contain a specific key/value pair. Fortunately, this is something that query_posts() can indeed help me with:

query_posts( $query_string . "&meta_key=foo&meta_value=bar" );

Be sure to set your desired order and orderby criteria as well. I’ve left those out of my example for brevity.

With our new query established, we can proceed to run through our own micro-loop:

if ( have_posts() ) :
  while ( have_posts() ) : the_post();
    // Do whatever you like here
    // <li><?php the_title(); ?></li>
  endwhile;
endif;

Once we’re done building a list of references to older (or newer) posts, we need to clean up a bit. We don’t want future queries to use our filter, so we need to remove that. Additionally, we should reset our query as well:

remove_filter( "posts_where", "filter_where_prev" );
wp_reset_query();

Voila! That’s it. Now to do this for both the previous and next items, I had to create two filters. Be sure to remove any filters you create immediately after using them, and always reset your query!

A Shorter Ternary Operator in PHP 5.3

The ternary operator is simply awesome. It allows for some really beautiful if-else style variable assignments:

$can_drink = ( $age >= 21 ) 
  ? true 
  : false ;

This operator let’s you evaluate a condition, and return one of two results based on that condition. In the example above we’re testing the legal drinking age. If the age is greater than or equal to 21, the value of $can_drink will become true (the first value after the question mark). Otherwise, the value of $can_drink will become false (the value after the colon) (this particular example doesn’t require a ternary operator as the condition evaluated will itself result in either true or false). You can test multiple conditions within the main ternary condition, but the rules still stay the same – if the main condition evaluates to true, the first result is returned, otherwise, the second result will be returned.

The operator is nice, don’t get me wrong, but it’s not always fun to play with. Suppose you’re searching for a value within an array and you would like to return it if found:

$job_title = array_search( "Jonathan Sampson", $emp )
  ? array_search( "Jonathan Sampson", $emp )
  : "n/a" ;

You’ll note that my white-spacing is a little different, but this won’t effect the results of the operator. What I’m doing here is checking to see if “Jonathan Sampson” is a value within the employees array. If “Jonathan Sampson” is in the array, I’d like to return the key for that entry, so I replicate the condition (which returns the key) in the first slot after the question mark so it will be returned if the condition is true. Otherwise, if “Jonathan Sampson” isn’t found in the array (and the condition returns false) I return the string “n/a”.

Either the $job_title variable will have a value like “Software Developer” (given the key for “Jonathan Sampson” is “Software Developer”) or it will be “n/a”. The problem here is that we’re performing the array search twice, which is really ugly. There’s another way we could do this:

$job_key = array_search( "Jonathan Sampson", $emp );
$job_title = $job_key ? $job_key : "n/a" ;

Now we’re only performing the array search once. The array_search function returns either the first key found, or FALSE. As such, $job_title will contain either the key, or the string. But this is still a bit ugly. We’ve got two lines, and repeated calls to the $job_key array.

In PHP5.3 we’re given the option of a much shorter ternary, eliminating the middle column completely. This is helpful when using functions like array_search() which themselves return the result we actually want. They serve both as the condition (since they will return FALSE when the value isn’t found) and the result (since they return the key if the value is found). Now we can do something like this:

$job_title = array_search( "Jonathan Sampson", $emp )  ?: "n/a" ;

Now, if array_search() finds the key, it’s automatically returned into the $job_title variable, else, “n/a” will be returned. Elegant.