Yearly Archives: 2011

Separating Posts by Post Format in WordPress

The Problem

WordPress has supported post formats for a couple of versions now, but I rarely ever see them being used. For this reason, I have decided to start using them myself—beginning with the “status” format. According to the Codex page, “status” posts represent short messages similar to those you would post on Twitter with the same 140-character limit. When I enabled them in my theme, I noticed that they were mixed in with the regular blog posts on the blog listing page. In my opinion, these little updates deserve their own space above the other posts.

The Solution

How did I achieve my goal? At first I added the function “has_post_format()” to show only regular posts, like so:

<?php while ( have_posts() ) : the_post() ?>
<?php 	if ( ! has_post_format('status') ) : ?>
	<!-- post loop html code goes here; omitted for brevity -->
<?php	endif; ?>
<?php endwhile; ?>

I preceded this with the following code (borrowed from a post on Stack Overflow) to only show the status updates:

<?php
$args 		= array( 'post_type'	=> 'post',
			 'post_status' 	=> 'publish',
			 'order' 	=> 'DESC',
			 'tax_query' 	=> array( array( 'taxonomy' => 'post_format',
							 'field'    => 'slug',
							 'terms'    => array( 'post-format-status' ) ) ) );
$status_updates	= get_posts( $args );
if ( $status_updates ) :
?>
<h1>Status Updates</h1>
<?php
foreach ( $status_updates as $post ) :
	setup_postdata( $post );
?>
<div id="post-<?php the_ID() ?>" class="post">
	<div class="post-meta">
		<h3><?php the_time( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ); ?></h3>
	</div>
	<div class="post-content">
		<?php the_excerpt(); ?>
	</div>
</div>
<?php
	endforeach;
endif; ?>

If you are intimately familiar with WordPress, this code should look fairly standard to you. The key part of this code is the “tax_query” key provided to the “$args” array and its subsequent values. Post formats are stored in their own taxonomy, with the name of the format prefixed by the string “post-format-” and stored as a term. (Hint: To show other formats, add them to the array as necessary or change the current key to which ever format you want to display.)

This worked great, but I wanted to make it more universal and easier to re-use. After some trial and error, I managed to modify a portion of the code from the first example to filter out the status updates.

function my_pre_get_posts( $query ) {
	if ( $query->is_posts_page && $query->is_main_query() ) {
		$query->set("tax_query", array( array( 'taxonomy' => 'post_format',
						       'field'	  => 'slug',
						       'terms'	  => array( 'post-format-status' ),
						       'operator' => 'NOT IN' ) ) );
	}

	return $query;
}
add_action( 'pre_get_posts', 'my_pre_get_posts' );

A WordPress hook, called “pre_get_posts“, intercepts the query used in the main loop for the post listing page. The “$query->is_main_query()“ is a new method introduced in WordPress 3.3 which ensures that we do not mess up any other queries being used, such as the one that retrieves the status updates. If you look closely, you’ll notice that I am re-using the previously mentioned “tax_query” argument but I have added the “operator” parameter to tell “WP_Query” that we want to ignore this specific term.

Caveats

There is a downside to this method, however. By removing the status updates from the main loop, the total number of posts (including the status updates) may be greater than your “max posts per page” setting thereby throwing your pagination off. In the future, I plan to find a way around this (probably by using the “paginate_links()” function and some simple math) but to me it is not that big of a deal right now.

Conclusion

As always, I hope that you have found this post useful and that it has helped you in some way. If you have a question, comment, or suggestion, do not hesitate to respond to this post using the form provided here or ask your question on the WordPress StackExchange.

<legal_disclaimer>
Please remember that the code that I have provided is for illustrative purposes only and may not be ready for use in production environments without further modification. I accept absolutely no responsibility for any damage or harm that may come to your site or anyone else’s site through your use or abuse of this code.
</legal_disclaimer>

Joe

December 17, 2011

Just added a Christmas theme that will be up for about the next week (until 12/25 or 12/26).

I’m Dreaming of a White Halloween

Wacky Weather

Central PA’s weather this year (2011) keeps getting stranger and stranger. In the last three months, we have experienced a magnitude 5.8 earthquake (my first) back in August, record flooding in September, and this month (October) the latest twist. We awoke this morning (10/29/11) to a freak snow storm. At first, the precipitation was a mixture of rain and snow and did not stick to the ground. Soon enough, though, it turned in to the pure fluffy white stuff and began sticking to everything including the ground and more importantly the roads. If travel is necessary, now is not the time to do it, but if you absolutely can’t avoid it, please be careful out there!

Wait, What?!

I have to admit that when saw the weather report last night on the late news, I was somewhat dubious that the storm was actually going to happen. As they say, “seeing is believing” and “a picture is worth a thousand words” so I have taken a few and included them with this post.

I’ve moved

I’ve moved – well, at least my site has anyway. When I set this site up back in August, I did not have any money in my budget for hosting as I had just started a new career at the beginning of that month. Temporarily, at least just to get the site started until I could afford hosting, I set my site up at XtreemHost under their free plan. XH is great for basic sites as it supports many of the same features as most entry-level paid hosting accounts, but unlike many other free hosts they do not stick ads or pop-ups anywhere on your page (only on PHP error pages in my experience but the “display_errors” INI setting is set to off by default unless you enable it in your .htaccess file). When it comes to running more advanced sites, such as those powered by a CMS like WordPress or Drupal, one quickly begins to hit a wall due to their limitations. PHP’s “mail()”, “fsock()”, and “cURL()” functions are disabled because of abuse by previous customers or at least that is their explanation. Fast forward to present-day October.  Now that I am a little more financially stable, and because I am sick of these restrictions impeding my development, I have decided it’s finally time to move my site to a HostGator “Baby” plan. Everything is now running much smoother and I am finally free to do whatever I want. I even managed to get my custom URL shortener, powered by YOURLS, to work at jleedy.tk.

On a side note, it is a very real possibility that I could actually be physically moving soon in order to be closer to my new place of employment. On Friday night, I looked at a beautiful apartment in Mount Joy and I mailed in the application on Saturday. I hope to hear something about it as soon as Wednesday if not tomorrow. I will post the news here if I do get it.

R.I.P. Dan Wheldon

As a long-time motorsports fan, I write this post with a heavy heart and wet eyes. Dan Wheldon passed away today in a fiery 15-car pile-up on lap 13 of the IndyCar season closer. My heart and my sympathies go out his young family that he left behind. The sport lost one of its greatest drivers and he will be greatly missed. For more information, please visit this post at ABCNews.

Fiery Crash on lap 13 of IndyCar finale
Birthday Balloons

Site Officially Launched

Happy Birthday!

That’s right, today is my 26th birthday and I have chosen to celebrate it by making it the official launch date of my new site. Event after six months of development, my site is still not quite complete but it will be soon so I decided to share my special day with it. What took so long? Originally, the design of this site was a final project for a class that I took back in the Spring of 2011 and the foundation was supposed to be a custom CMS that I was writing in Ruby on Rails as a learning experience. In August of 2011, shortly after beginning my employment at Paradox Labs, I chose to make the switch to WordPress in order to learn valuable skills necessary for my new career. This is the second personal site that I have done for myself, the previous one being josephleedy.info back in 2009. Today is also Google’s 13th birthday. Enough history, let’s celebrate already!

Birthday Cake

Comparing values from multiple jQuery UI Datepickers

Intro

The other day I was working on a project for a client at Paradox Labs which required a form where a user could enter a start date and time for an event as well as an end date and time. To accomplish this task, I used Trent Richardson‘s wonderful Timepicker add-on. This tutorial was written using it, but the code should also work with a standard datepicker since I am actually hooking into its events.

If you just want to see the code, you can skip to the solution or view the jsFiddle fiddle.

The problem

When using multiple datepickers, it may be necessary to make sure that the user has chosen the correct dates and times. Naturally, an event could span one or more days or hours but it is highly unlikely that it would start now or in the future and end in the past without a time machine. Likewise, an event would not start after it has already ended. How do we prevent this from happening?

The solution

By converting the dates and times selected to milliseconds and comparing those values, a time-bending paradox is averted. Here is what I came up with:

If you look closely at the code (in particular the CheckTimes function), you’ll see that I am using the JavaScript object method Date.parse to do the conversion along with some standard operators (“>=” and “<=”) to do the comparison. Problem solved! Play with the fiddle to see how it works. (The rest of the code is provided for demonstration purposes.)

References

Notes

This brief tutorial assumes that you are at least somewhat familiar and comfortable with the jQuery JavaScript framework. If you need some help, don’t hesitate to contact me or – even better – post your question on StackOverflow or the WordPress StackExchange (wherever most appropriate).

Make your WordPress category list valid by removing the “rel” attribute

The Problem

WordPress is a great blogging platform, but like anything in life it does have its shortcomings and flaws. While trying to validate my site as HTML5, I ran into one such issue. The functions “the_category” and “wp_list_categories” use the file “/wp-includes/category-template.php” to output the HTML that lists all categories for a particular post or set of posts. If you take a look at that file (line 163, function “get_the_category_list”) , you’ll notice that it adds the attribute ‘rel=”category tag”‘ to the links that it produces. While “tag” is a valid value for rel, “category” is not according to this list found at microformats.org. This causes the W3 Validator to throw an error stating “Bad value category tag for attribute rel on element a: Keyword category is not registered.”

The Solution

How do we fix this problem? Simple – either remove the word “category” from the “rel” attribute, or remove the “rel” attribute all together. The following PHP code sample will do the latter, when placed in the current theme’s “functions.php” file. If you are not comfortable editing PHP code directly or messing with your theme, I plan to update this post sometime in the future with a plug-in that will do this automatically so please stay tuned.

Without further ado:

function remove_category_list_rel( $output ) {
	// Remove rel attribute from the category list
	return str_replace( ' rel="category tag"', '', $output );
}

add_filter( 'wp_list_categories', 'remove_category_list_rel' );
add_filter( 'the_category', 'remove_category_list_rel' );

This function works by using the PHP function “str_replace” to replace the “rel” attribute with an empty string and is called by registering a WordPress filter.

Hopefully you will find this little piece of code useful and my explanation clear enough to understand it. If you have anything to say, or you need help getting this to work, please add a comment using the form below and I will do my best to get back to you. Thanks for reading!

Introduction

Welcome to my new blog! This will be a place for me to gather my thoughts. Subjects that I hope to blog about include my Geocaching adventures, computer repair, Web development, cars/motorcycles, sports, and life in general. I hope that you will find my words to be a good read. Who knows, maybe you’ll even learn something!