Author Archive

6/19/2008 ↓

How to: Offsets and Paging 19comments

If you like this post, please subscribe to our RSS feed to read our new posts every day.

Reader John writes in:

How does one use paging with an offset? Doing so breaks the navigation controls.

The problem with using an offset in a query is that WordPress ignores any reference to paging. In other words, you can use an offset and paging, but not both together.

This can be solved by tapping into the post_limits filter.

Step 1: Add the ‘my_post_limit’ Function

The my_post_limit function is what the post_limits filter will use to update the standard loop query.

We’ll use the function to use paging and offsets together. This function should be placed in your theme’s functions.php file.


function my_post_limit($limit) {
	global $paged, $myOffset;
	if (empty($paged)) {
			$paged = 1;
	}
	$postperpage = intval(get_option('posts_per_page'));
	$pgstrt = ((intval($paged) -1) * $postperpage) + $myOffset . ', ';
	$limit = 'LIMIT '.$pgstrt.$postperpage;
	return $limit;
} //end function my_post_limit

Step 2: Add the Filter Reference


<?php add_filter('post_limits', 'my_post_limit'); ?>
<div id="recent">
<h3>Recent Articles</h3>

In the above code, I add a filter for post_limits, which will call the my_post_limit function mentioned in Step 1.

Step 3: Start Your Loop

In this loop, we’ll be declaring a global variable called $myOffset. This will be the offset we’d like to have and is used by the my_post_limit function.


<ul>
<?php
global $myOffset;
$myOffset = 1;
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('offset='.$myOffset.'&showposts=5'.'&paged='.$paged);
?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
        <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Step 4: Enable Navigation

We’re just adding the standard next/previous links at the end of the loop.


<div class="navigation">
  <div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
  <div class="alignright"><?php next_posts_link('More &raquo;') ?></div>
</div>
</div>

Step 5: Remove the Filter

In this step, we’ll be removing the post_limits filter and assigning the query back to its original value thanks to a temporary placeholder.


<?php $wp_query = null; $wp_query = $temp;?>
<?php remove_filter('post_limits', 'my_post_limit'); ?>

Step 6: You’re done!

Using the above code, you should now be able to use offsets and paging together.

Here is a downloadable file of all the code mentioned in this post.

Thank you John for asking such a great question.

Tags:

6/8/2008 ↓

Comment Remix - Video Plugin Review 8comments

If you cannot see, the video, please visit this link: Comment Remix - Video Plugin Review

Today’s WordPress Plugin video review is of Comment Remix.

Video Summary: Comment Remix adds numerous admin panel options, as well as reply, quote, and tag capabilities on a post. The star feature for admins (in my opinion) is the “In Need of Reply” option, as well as the various actions added to comments.

Pros: Reply/Quote options are useful for admin and end-users. “In Need of Reply” is great for blog admins and unreplied comments. A lot of admin panel options make this plugin highly configurable.

Cons: Pop-up boxes could use the built-in WP 2.5 thickbox.js script. The “In Need of Reply” badly needs an “ignore all” option. Not sure of the usefulness of tags for comments unless there are global options. Styling could also be better for the comment actions.

The Comment Remix plugin is entered in the WLTC Plugin Competition. Please head over and give your say to the Comment Remix plugin.

For a text review, please read Plugin Review - WP Comment Remix.

If you think your WordPress plugin will merit itself to a video review, please get in contact with me via e-mail (ronalfy+wltc @ gmail dot com). Please keep in mind I will not review premium plugins.

For more videos, please check out our brand new video website at Weblog Tools Videos.

6/7/2008 ↓

Plugin Deactivation Issues Solved With Actions and Filters 8comments

When Jeff wrote about plugin deactivation breaking your blog, Aaron and I wrote in the comments of a few solutions to prevent plugin issues with themes.

Within this post I will present several techniques plugin and theme authors can take in order to prevent deactivation issues.

Method 1: function_exists

In this example, let’s assume we have a function named related_posts.

When in a theme, we could use this code to call the function if only it exists.


<?php if (function_exists("related_posts")) {  related_posts(); } ?>

The PHP function_exists checks for the existence of the function, and if it does exist, it calls the function.

Method 2: function_exists and Actions

Using the same function name, the theme author could add some code into their functions.php file and use an action and function_exists combination.


if (function_exists('related_posts')) {
	add_action('my_related_posts', 'related_posts');
}

In the above example, we create a new action called my_related_posts.

The end user would use the do_action function where he wants the function used:


<?php do_action('my_related_posts'); ?>

Method 3: Actions

To use pure actions, the plugin author would have to take the initiative and add associated actions to their plugin code.

The code would look very similar to method 2, but would be included in the plugin file.


add_action('my_related_posts', 'related_posts');

The end user would then do the simple do_action call.


<?php do_action('my_related_posts'); ?>

Method 4: function_exists and Filters

Say, for example, there’s a plugin with a template tag that returns some code that you can then echo out in a theme.

Let’s pretend for a minute that the related_posts function could return a string instead of automatically spitting out the code to the screen.

In this case, the template author could add some code into their functions.php file.


if (function_exists('related_posts')) {
	add_filter('my_related_posts', 'related_posts');
}

The end user would then add the following to their theme:


<?php $s =  apply_filters('my_related_posts'); echo $s; ?>

Method 5: Filters

Again, the plugin author would have to take the initiative to only use filters. The plugin author would add the following to their code.


add_filter('my_related_posts', 'related_posts', 1, 2);

The above filter has a priority of one and accepts two arguments.

The end user (aka, theme tweaker), would add very similar code as used in method 4.


<?php $s =  apply_filters('my_related_posts', 4,10); echo $s; ?>

Method 6: Actions and do_action_ref_array

Let’s assume the plugin author has added in the appropriate code to their plugin:


add_action('my_related_posts', 'related_posts', 1, 1);

The above related_posts action just adds an action at priority one, which accepts one argument.

The themer could then add a reference to this action using the do_action_ref_array function.


<?php do_action_ref_array('my_related_posts', array(3,20)); ?>

Assuming the my_related_posts action takes two arguments, we use an array to pass the necessary arguments.

Conclusion

As mentioned in the introduction, it’s the plugin or theme author’s responsibility of adding in the necessary actions and filters so that the end user can deactivate plugins without any major headaches.

The methods I mentioned are not exhaustive, and can be far more advanced if need be. If you have any questions, please leave a comment.

For any code, please use Pastebin and provide a link.

Tags:

5/29/2008 ↓

Removing Width/Height from the Image Uploader 30comments

Reader Vivien writes in:

Is there a way to prevent WordPress from inserting the width and the height for images in the new 2.5 media manager?

In short, yes, but it requires you to insert some code into your theme’s functions.php file.

Fortunately, there is a WordPress filter we can use called image_downsize, which takes in three arguments (a boolean, an attachment ID, and a size string).

add_filter('image_downsize', 'my_image_downsize',1,3);

All I’m doing in the above filter is setting the filter name, the function to call (my_image_downsize), what priority I want the filter, and how many arguments the function takes.

From there, I mimic the function image_downsize in the ‘wp-includes/media.php’ file, but do not return a width or a height. As a result, when the image is sent to the editor, no width or height is present.

function my_image_downsize($value = false,$id = 0, $size = "medium") {
	if ( !wp_attachment_is_image($id) )
		return false;
	$img_url = wp_get_attachment_url($id);
	//Mimic functionality in image_downsize function in wp-includes/media.php
	if ( $intermediate = image_get_intermediate_size($id, $size) ) {
		$img_url = str_replace(basename($img_url), $intermediate['file'], $img_url);
	}
	elseif ( $size == 'thumbnail' ) {
		// fall back to the old thumbnail
		if ( $thumb_file = wp_get_attachment_thumb_file() && $info = getimagesize($thumb_file) ) {
			$img_url = str_replace(basename($img_url), basename($thumb_file), $img_url);
		}
	}
	if ( $img_url)
		return array($img_url, 0, 0);
	return false;
}

Download the Code

Here is a sample functions.php file of the code presented in this article.

I also used Andrew’s plugin generator to quickly put together a plugin that I will creatively call No Image Width or Height (download link). It will accomplish the same thing for those not comfortable with code. Just unzip, place in your WordPress plugin’s folder, and activate.

Thanks Vivien for the interesting question.

5/24/2008 ↓

Dashboard Widget Manager - Video Review 6comments

If you cannot see, the video, please visit this link: Dashboard Widget Manager - Video Plugin Review

Today’s WordPress Plugin video review is of Dashboard Widget Manager by Viper007.

Video Summary: Dashboard Widget Manager is a great way to customize the WordPress 2.5 dashboard. The plugin is great for multi-author blogs where each author would like a customizable dashboard. Admin can also set a default dashboard setup.

The ability to re-order and customize certain dashboard widgets is a very nice feature. If possible, I’d like to see some extra widgets in the future.

Pros: Customizing the dashboard is very easy if you are familiar with widgets.

Cons: Minor style issues.

If you think your WordPress plugin will merit itself to a video review, please get in contact with me via e-mail (ronalfy+wltc @ gmail dot com). Please keep in mind I will not review premium plugins.

For more videos, please check out our brand new video website at Weblog Tools Videos.

5/17/2008 ↓

How To: Avoid Duplicate Posts 21comments

A reader writes in:

I’m developing a new theme and I’m having trouble getting duplicate posts from showing when running two loops (one standard loop and one from a specific category). Even when I copied the specific code from directly from the codex, it was not working.

The Codex article the reader mentioned was regarding the Loop. Although the example shows how to avoid a single duplicate post, it doesn’t show how to avoid duplicating multiple posts.

Here’s how to show two individual loops without duplicating posts in either loop.

Step 1: Add a ‘posts_where’ Function

A WordPress filter is needed to accomplish this, and we’re going to be tapping into the ‘posts_where‘ filter.

The reason being is we need to modify the query used for the loop and exclude some posts.

Here’s the function we’ll be using called post_strip:

function post_strip($where) {
	global $myPosts, $wpdb;
	$where .= " AND $wpdb->posts.ID not in($myPosts) ";
	return $where;
}

In the above code, I use a global variable called $myPosts, which is comma-separated string of post IDs to exclude.

Step 2: Start the First Loop

Within this first loop we’ll be keeping track of the post IDs being used. Nothing fancy is being done here. We’re just pulling the last five posts posted.

<?php
global $myPosts;
$myPosts = '';
?>
<div>
<?php
$my_query = new WP_Query();
$my_query->query('showposts=5');
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post(); ?>
<?php $myPosts .= $post->ID . ","; ?>
<div><?php the_title(); ?></div>
<!-- Post Stuff -->
<?php endwhile; endif; ?>
</div>

Pay special attention to the $myPosts variable, which is used to keep track of all of the post IDs.

Step 3: Add the Filter

We’ll now need to add a posts_where filter for the second loop. This filter will use the post_strip function we started in Step 1.

<?php add_filter('posts_where', 'post_strip'); ?>

Step 4: Start the Second Loop

The second loop is a repeat of the first loop to demonstrate that the posts are not being duplicated. The second loop uses a different loop technique since paging isn’t necessary.

<div>
<?php
$my_query = new WP_Query('showposts=5');
while ($my_query->have_posts()) : $my_query->the_post();?>
<div><?php the_title(); ?></div>

<!-- Post Stuff -->

<?php endwhile; ?>
</div>

Step 5: Remove the Filter

The filter we added in Step 3 now needs to be removed.

<?php remove_filter('posts_where', 'post_strip'); ?>

Step 6: Admire the Results

Before Duplicates Being Shown
Before - Duplicates Being Shown

After - Duplicates Removed
After - Duplicates Removed

Downloadable Code

Here is a sample index.php for download.

5/4/2008 ↓

Error Management for WordPress Plugins 10comments

For the past few weeks I’ve been working on a WordPress plugin. One of my goals was to have fancy and relevant error messages.

I contemplated writing my own error manager, and even began a very basic one. I experienced hurdle after hurdle, and finally I thought to myself, “Wouldn’t WordPress have its own error manager also?”

So I did a quick source-code search and came across the WP_Error class.

One of the hurdles I ran into in creating my own error manager was error localization. The WP_Error class makes localizing error messages extremely simple.

Adding Error Messages

To add an error message, the first thing you’ll want to do is instantiate your own instance of WP_Error.

$myErrors = new WP_Error();

The next step is to add in your error messages.

$myErrors->add('access_denied', __('You do not have permission to do that.',$myLocalizationName));

There are a few things to notice here. There is something called an error code, which you will use to look up the full error message. You also have the full error message, which uses the __ function for localization.

Retrieving Error Messages

After you have added in your error messages, you’ll want to retrieve them at some point.

Retrieving an error message is as simple as calling the get_error_message method and passing it your error code.

$errorMessage = $myErrors->get_error_message($code);

From there you can echo out your message in whatever manner suits you.

Applications

Using the WP_Error class is ideal for those with themes and plugins.

For plugins, it’s best to have your errors as a member of a class. Using the class approach assures that you can access the errors throughout your methods, and also avoid naming conflicts.

For themes, you can also create your own class, or have a prefixed variable so you don’t have possible conflicts with other variables.

Downloadable and Example Code

Here is some downloadable code with an example of how the class might be used in a theme. As stated earlier, plugin authors may want to use a class for this.

The code is assumed to be placed in a theme’s “functions.php” file.

class my_class {
	function my_class() {
		$this->localizionName = '';
		$this->errors = new WP_Error();
		$this->initialize_errors();
	}
	/* get_error - Returns an error message based on the passed code
	Parameters - $code (the error code as a string)
	Returns an error message */
	function get_error($code = '') {
		$errorMessage = $this->errors->get_error_message($code);
		if ($errorMessage == null) {
			return __("Unknown error.", $this->localizionName);
		}
		return $errorMessage;
	}
	/* Initializes all the error messages */
	function initialize_errors() {
		$this->errors->add('my_weird_error', __('Some weird error has occurred', $myLocalizationName));
		$this->errors->add('access_denied', __('You do not have permission to do that.',$myLocalizationName));
	} //end function initialize_errors
}
$myErrors = new my_class();
echo $myErrors->get_error('my_weird_error');

The above code has two helper methods, one which retrieves the errors, and one which initializes the errors. The example is very basic, but should give you a good idea on how to use the WP_Error class.

Conclusion

There are many features of the WP_Error class not mentioned here, but you can dissect the code yourself if you like. The class is found in the wp-includes folder under classes.php.

The WP_Error class is a simple and powerful way to store errors, and output them rather easily. And the best thing, the messages can be localized.

Tags:

4/21/2008 ↓

Organize Series - Plugin Video Review 6comments

If you cannot see the video, please visit this link: Organize Series - Video Plugin Review

Today’s WordPress Plugin video review is of Organize Series by Unfolding Neurons.

Video Summary: Organize Series is an extremely powerful plugin that makes organizing series rather simple. There are many options to customize the look. The show clincher for me is the ability to have series archives. I highly recommend this plugin for people who do post series.

Pros: It’s easy to add series and to organize them. Many options to customize the look and feel. The series permalinks are a nice feature.

Cons: Perhaps too many options, but power-users will love them. I only tested this plugin on 2.5, so I’m not sure how well this plugin fares on other versions.

If you think your WordPress plugin will merit itself to a video review, please get in contact with me via e-mail (ronalfy+wltc @ gmail dot com). Please keep in mind I will not review premium plugins.

For more videos, please check out our brand new video website at Weblog Tools Videos.

4/20/2008 ↓

Baltic Amber Admin Themes for WordPress 2.5 17comments

Kaspars from Konstruktors has released a WordPress 2.5 plugin called Baltic Amber Themes that allows you to change your default colour schemeadmin theme.

Update: This plugin does modify your admin layout as well as your color schemes, so please keep this in mind if trying the plugin out. Kaspars has mentioned that there is now an option to disable the layout changes.

What’s even cooler about this plugin is that the plugin provides a nice refresh to the Write Panel and several areas of the overall administration panel.

After activating the plugin, you can change the default colour schemetheme by viewing your profile options. From there, you have an option of 8 colour schemes, or an option for a custom or random colour.

This is a rather welcome addition to the WordPress 2.5 admin area.

baltic-amber-colour-schemes.jpg
Baltic Amber Themes

Baltic Amber Write Panel
Baltic Amber Write Panel

Baltic Amber Settings
Baltic Amber Settings

Download your own copy of Baltic Amber Admin Themes.

Tags:

4/19/2008 ↓

Paging and Custom WordPress Loops 43comments

Last week I published two articles using custom loops. The first was about how to create a custom loop. The second was how to retrieve posts based on custom fields. In both articles, several readers commented that they would like to see paging and have it explained.

I’d like to thank Aaron Harun from Anthology of Ideas for supplying the code used in this post.

Paging, and why it doesn’t work with WP_Query

The paging magic happens in a file called ‘link-template.php‘ in the ‘wp-includes‘ folder.

Most themes have basic paging built in, with the help of two functions: next_posts_link and previous_posts_link.

These functions, as well as several others, make use of a global variable called $wp_query. This variable is actually an instance of the WP_Query object. However, when we create our own instantiation of WP_Query, we don’t have this global variable $wp_query, which is why paging will not work.

How to make paging work with a custom loop

As Aaron mentioned, the paging functions rely on a global variable called $wp_query. The “fix” is to trick WordPress into using the global $wp_query variable when using our own custom loops.

In the example below, I’ll show how to display the last five recent articles with our own custom loop with paging intact.

<h3>Recent Articles</h3>
<ul>
<?php
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('showposts=5'.'&paged='.$paged);
?>

The first thing the code does (shown above) is create a temporary variable to hold a reference to global variable $wp_query. The wp_query variable is set to null, and we instantiate a new WP_Query object.

Notice in the query above that we have these parameters:

$wp_query->query('showposts=5'.'&paged='.$paged);

The paged portion of the query is critical in order to have paging.

From there, we can now do our own query and begin our custom loop.

<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
	<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Notice in the above code that the loop is initiated using the $wp_query variable. Since we are using $wp_query, paging should work.

Now it’s time to create our navigation links for paging:

<div class="navigation">
  <div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
  <div class="alignright"><?php next_posts_link('More &raquo;') ?></div>
</div>

And finally, we assign the variable $wp_query back its original value using the $temp variable we set earlier.

<?php $wp_query = null; $wp_query = $temp;?>

The Full Code

<h3>Recent Articles</h3>
<ul>
<?php
$temp = $wp_query;
$wp_query= null;
$wp_query = new WP_Query();
$wp_query->query('showposts=5'.'&paged='.$paged);
?>
<?php while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
	<li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<div class="navigation">
  <div class="alignleft"><?php previous_posts_link('&laquo; Previous') ?></div>
  <div class="alignright"><?php next_posts_link('More &raquo;') ?></div>
</div>
<?php $wp_query = null; $wp_query = $temp;?>

Additional Applications

The above technique can allow paging for custom loops. All you have to do to modify this is to use your own query parameters, and change the code within the custom loop.

recent-articles-screenshot.jpeg
Recent Articles Example

The above example is live at raproject.com under Recent Articles.

Conclusion

Paging is a powerful WordPress feature, and fortunately you can use it when defining your own custom loops.

The example I demonstrated was rather generic, but hopefully you’ll be able to apply it to your own custom loops where paging is necessary.

Please feel free to share your own examples or problem code in the comments. If you use code, please use something like pastebin since some code isn’t allowed in the comment section.

4/14/2008 ↓

Absolute Comments - Plugin Video Review 13comments


If you cannot see, the video, please visit this link: Absolute Comments - Video Plugin Review

Today’s WordPress Plugin video review is of Absolute Comments by PlanetOzh.

Video Summary: Absolute Comments is a major improvement over the WordPress 2.5 Comments Panel. The plugin allows you to reply to comments easily without having to visit a post. The plugin also allows you to view all comments for a particular post. An immense timesaver.

Pros: Major improvement over the existing WordPress 2.5 comments panel. The plugin makes it easy to reply to comments.

Cons: None, although it would be nice if there was a way to change the default reply text (or have several options) in the admin-panel without having to edit the plugin’s code.

If you think your WordPress plugin will merit itself to a video review, please get in contact with me via e-mail (ronalfy+wltc @ gmail dot com). Please keep in mind I will not review premium plugins.

For more videos, please check out our brand new video website at Weblog Tools Videos.

4/13/2008 ↓

How to Only Retrieve Posts With Custom Fields 24comments

One question I come across a lot regarding custom fields is how to only retrieve posts based on a custom field.

For example, if a post has a custom field of “MyData”, someone might want to only retrieve that particular post.

The WordPress Codex has a technique for retrieving posts based on custom fields, which consists of writing your own query and going through the results.

The technique in the Codex is good, but I’ve found a re-usable way one can retrieve only posts with certain custom fields.

The technique I use makes use of two custom functions placed in a theme’s “functions.php” and a custom WordPress Loop.

Let’s get started — The “functions.php” file

First, let’s place the two custom functions in the “functions.php” file. This file should be in your theme directory, but if it isn’t there, you can create one using any text editor.

Here are the two functions below:

function get_custom_field_posts_join($join) {
	global $wpdb, $customFields;
	return $join . "  JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
	global $wpdb;
	$group .= " $wpdb->posts.ID ";
	return $group;
}

The function “get_custom_field_posts_join” makes use of an advanced WordPress filter called “posts_join“. Each time posts are called, you can add on extra MySQL parameters using filters. In this case, I add on an option to find certain postmeta. Please note the use of a global variable called “customFields“, which I’ll explain a bit later.

The function “get_custom_field_posts_group” makes use of another advanced WordPress filter called “posts_group“. This is used to avoid duplicate entries in our return query.

Now Let’s Work on Our Loop

After the two functions are placed in the “functions.php” file, it’s time to work on placing the appropriate code into one of our template files.

For this example, I’ll be modifying the “sidebar.php” file in the WordPress default theme. You could place the below code in any of your theme files, however.

<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'Links', 'MyData'"; //Comma seperated 's1', 's2', 's3'

The first part of the code deals with establishing the structure of the output. You really could do anything you want here.

Please note the use of the global variable “customFields“. What we’re doing here is setting up a comma-separated variable that will be used to search for our custom fields. The “customFields” variable is used in the “get_custom_field_posts_join” function.

In this example, it is assumed we want to find posts with custom fields of “Links” and “MyData“.

Custom Fields - Links and MyData
Custom Fields - Links and MyData

The next bit of code instantiates a new instance of WP_Query and runs a query to return some posts.

$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');

Note the use of the “add_filter” and “remove_filter” functions. Since we are doing a post query, we can tap into the query and add our own parameters. So before the query is initiated, two query-type filters are added, and after the query is initiated, the two filters are deactivated since we only want them run once.

This last bit of code initiates our custom loop, gets the custom values, spits them out, and ends the loop.

while ($customPosts->have_posts()) : $customPosts->the_post();
$links = get_post_custom_values("Links");
$data =  get_post_custom_values("MyData");
?>
<li><a href='<?php echo $links[0]; ?>'><?php echo $data[0]; ?></a></li>
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>

The “get_post_custom_values” WordPress function returns an array of matching keys. It’s assumed there is only one key per post, which is why we echo out the first value (Ex: echo $links[0]).

The Full Post Code

Here is the full post code. The only thing you need to change for your own use is the custom fields needed (change the customFields text) and what type of output is desired within our custom loop.

<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'Links', 'MyData'"; //Comma seperated 's1', 's2', 's3'
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$links = get_post_custom_values("Links");
$data =  get_post_custom_values("MyData");
?>
<li><a href='<?php echo $links[0]; ?>'><?php echo $data[0]; ?></a></li>
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>

Custom Field Output
Custom Field Output

Downloadable Code

The full code mentioned in this post is available for download. Within the “zip” file are a sample “functions.php” and “sidebar.php“.

Conclusion

With the above technique, you can do some pretty fancy stuff. For example, you can only retrieve posts with custom images for a nice magazine effect.

If you have any questions regarding the code, I’ll do my best to answer them in the comments.

Define Your Own WordPress Loop Using WP_Query 38comments

We all know what the WordPress Loop is right? If not, there are many great tutorials around the web that explain the WordPress Loop.

One of the easiest ways to navigate and manipulate the loop is to use the function called query_posts. Nathan Rice calls it a WordPress developers best friend.

When you use query_posts, however, you risk the following:

  • Potential to interfere with plugins which make use of the Loop.
  • Potential to invalidate WordPress conditional tags.
  • Having to deal with resetting, rewinding, offsetting…

I say skip query_posts. In a way you’ll still be using it, but the better (and sometimes easier) technique is to instantiate your own WP_Query object and create your own loop.

Creating Your Own Loop With WP_Query

The first step is to instantiate your own variable using the WP_Query class.

What we’ll be doing in this example is creating a common feature on blogs, which is to display a list of the recent articles.

<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>

All I’ve done in the above code is defined a variable named recentPosts and instantiated an instance of WP_Query.

I then used a method of WP_Query to start a query (pretty much the same thing as using query_posts). You even use the same usage parameters as query_posts.

Now it’s time to start our own loop:

<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
   <!-- do some stuff here -->
<?php endwhile; ?>

Notice the use of the recentPosts variable to start the loop. We utilize two methods of WP_Query, which is have_posts and the_post. You can read more about those two methods on my article Global Variables and the WordPress Loop.

The beauty of this is that once you are inside your own loop, you can use the standard post tags.

The Full Code

Here’s the full code for showing the last five recent posts using your own loop:

<h3>Recent Articles</h3>
<ul>
<?php
    $recentPosts = new WP_Query();
    $recentPosts->query('showposts=5');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
    <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>

Update: Using Pagination

This comment is from Aaron Harun -

@Ron and Monika

If you use the query:

$recentPosts->query('showposts=5'.'&paged='.$paged);

it will automatically page the wury based on the page number passed
through the url eg "/page/4"

However, this doesn't work with the “post_nav_link” function because it
only checks the $wp_query variable. To get around this you have to
trick the function by switching $wp_query on it. Add the first block
before your custom loop and the second after to achieve this effect.

<?php //query_posts('paged='.$paged);
$temp = $wp_query;
$wp_query= null;
   $wp_query = new WP_Query();
   $wp_query->query('showposts=5'.'&paged='.$paged);
?>

<?php $wp_query = null; $wp_query = $temp;?>

Thanks Aaron for the contribution.

Conclusion

Defining your own loop using WP_Query is an easy way to run your own custom queries without interfering with the default Loop. It’s also a great way to run multiple loops that are completely independent of each other.

WordPress Resources mentioned:

4/7/2008 ↓

Admin Favicon Plugin Video Review 3comments

Today’s WordPress Plugin video review is of Admin Favicon by John Kolbert.

Video Summary: Admin Favicon is a plugin for those who have a lot of open tabs and would like to use a Favicon to show using the WordPress Administrative Panels.

Pros: Extremely simple to use and quite useful for those who have a lot of open tabs in their browser. Very light-weight script.

Cons: None. Admin Favicon is not ideal for those who use desktop publishers or browsers without tabbed support.

If you would like your own plugin reviewed, please get in contact with me via e-mail (ronalfy+wltc @ gmail dot com). Please keep in mind I will not review premium plugins.

For more videos, please check out our brand new video website at Weblog Tools Videos.

4/2/2008 ↓

WordPress 2.5 Upgrade Guide(s) 69comments

There are many guides out there (one in particular I won’t dare mention) about upgrading to 2.5, but I was curious how your experience was.

I’ve personally upgraded two of my blogs — one manually, and one using Keith’s awesome WordPress Automatic Upgrade plugin. In both cases, I ran into no issues aside from a few incompatible plugins (you did check the list, right?).

To get the ball rolling, here are several links to some upgrade experiences around the web. My hope is to make this post a resource with a list of upgrade guides and experiences. Please feel free to add your own in the comments below (only one link please).

So what was your upgrade experience like?

S2