Archive for the 'WordPress Hack' Category

7/11/2008 ↓

WordPress for iPhone App 16comments

Thanks for visiting! If you're new here, you may want to subscribe to our RSS feed. This blog posts regular Wordpress news, updates of themes, plugins, ideas, hacks, quick fixes and everything about blogging, especially about Wordpress. Go ahead, subscribe to our feed! You can also receive updates from this blog via email.

WordPress for iPhone: Big news from the Automattic team yesterday. They released a first look at their iPhone App that works on both WordPress.com and WordPress.org blogs. The application is Open Source, available from the iPhone App store and will be available for free. The screen real estate problem with the large on screen keyboard looks to be largely solved with this app and it adds the ability to modify previous posts and view your blog on the web. The official iPhone app for WordPress blog is linked above. The application received rave reviews from a variety of sources such as TechCrunch and Webware and ma.tt talked about it yesterday. Check out the screencast when you get a chance. It definitely has a wow factor.

Tags:

6/19/2008 ↓

How to: Offsets and Paging 14comments

Author: Ronald Huereca Category: HOW-TO, WordPress Hack

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/11/2008 ↓

Hiding Advertisements For Single Posts 29comments

Author: Keith Dsouza Category: HOW-TO, WordPress Hack

There are many plugins which are useful when it comes to displaying ads to your visitors but there are only a few of them which allow you to determine to whom and when you should. Who Sees Ads does help you to determine to whom and when you should display advertisements, though, there is a limitation with the plugin as it does not allow you to control the ads shown on single post level.

In this post we will talk about the quick and easy way to hide advertisements for any particular post by making some minor changes to your theme.

The Condition To Skip Advertisements For Single Posts

Talking about conditions whatever you do there is always a condition under which you perform any action. We will use a similar logic and create conditions under which the advertisements should not be displayed for certain posts.

The condition we will be using is quite simple and will fulfill the following statement, ” if something happens do this otherwise do something else”.

This can be simplified into lay terms as “if you are hungry buy a burger” “else don’t buy a burger”. As you can see the conditions you apply are quite simple and pertain to you to doing some kind of activity under different conditions.

The Code To Skip Advertisements In Single Posts

To skip advertisements for single posts you will have to manually edit the file “single.php” of your current WordPress theme. I recommend you edit your theme through the WordPress Admin Panel since it will help you catch any errors and save you a lot of trouble.

Once you have opened the single.php navigate to the place where you have placed the advertisements and change the code within the WordPress Loop from;

…………

Your Advertisement Code

…………

to;

if(get_the_ID() != xx) {

…………

Your Advertisement Code

…………

}

Replace xx with the post id for the post which you do not want to show advertisements for. You can also skip multiple posts from displaying advertisements by adding the OR condition in the following way;

if(get_the_ID() != xx || get_the_ID() != xx) {

…………

Your Advertisement Code

…………

}

For those who are unaware of programming “||” represents OR in programming language and if you are curious AND is represented by “&&”.

How do you get the IDs of the posts you want to Skip Advertisements for?

To find the IDs for the posts you want to skip advertisements for, you will need to login to your WordPress administration panel and navigate to the Manage option. Once there find the post you want to skip the advertisement for and hover over it, you should see the ID of the post in your status bar. Check the screenshot below;

find-post-id

If you do not see the id in the status bar you can find out the ID by clicking on the post and going into edit mode where you will see the ID for the post in the URL.

find-post-id-address-bar

Once you make the changes to your advertisements they will not display for the posts you chose to skip.

If you do have any questions feel free to ask them in the comments and I would be more than happy to answer them.

Note: This trick will not work if you use external plugins to display your ads and is only valid when you display ads by hard coding them into your themes.

Tags:

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/17/2008 ↓

How To: Avoid Duplicate Posts 15comments

Author: Ronald Huereca Category: HOW-TO, WordPress, WordPress Hack

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.

4/28/2008 ↓

Exporting-Importing A Category 15comments

Author: Jeff Chandler Category: HOW-TO, WordPress, WordPress Hack

When it comes to exporting, WordPress already does a wonderful job with it’s support to export posts, pages, comments, custom fields, categories, and tags. However, there is a problem. The WordPress exporter lacks granularity. What I mean by this is that, the exporter covers the entire blog instead of being able to select certain categories to export. I’ve searched the WordPress Plugin database high and low to look for a plugin that would specifically export categories and I could not find one. I did manage to come across two techniques though that get the job done.

There are two ways to export specific categories. The first is to read this forum post where HandySolo explains how to use the category RSS feed to export specific categories from a self hosted blog to a WordPress.com blog. The problem with this method is that, none of the meta data attached to the posts are carried over with the posts.

The second method is not pretty but it gets the job done. What I ended up doing was creating a new user account on my blog. I then used the post manager and filtered the posts by the category for which I wanted to export. I went through each individual post and quickly changed the post author from the original account, to the newly created user account. In my case, I had to do this to 25 individual posts. What is annoying about this method is that, when you save a post under a new author name, any blogs or posts that you have linked to within those posts will end up resending PINGs. However, I believe if you turn off this setting under the SETTINGS-DISCUSSION link in your administration panel this will prevent that from happening. Just remember to turn that back on after you’re finished.

After all of the posts within the category have been reassigned to a new author, you are ready to export. In your WordPress administration panel browse to MANAGE - EXPORT. Now here is the important step. Underneath where it says OPTIONS, you have a drop down box where you can restrict the export to a certain author.

WordPress Export Options

In the drop down box, select the newly created author and click on the DOWNLOAD EXPORT FILE and a WordPress WXR file will be downloaded to your desktop. This file will contain all of the posts from the category you wanted to export because the new user you created was assigned to only those posts within that category. This method actually allows you to export specific categories while maintaining the meta data associated with those posts such as comments and tags.

This is probably not the best way to obtain these results but it’s the only method that I’ve found that allows me to export specific posts/categories while still having all of the other data attached to those posts. If you have a better solution or know of a plugin that can obtain the same results, I’d be very interested to know about it.

4/19/2008 ↓

Paging and Custom WordPress Loops 29comments

Author: Ronald Huereca Category: HOW-TO, WordPress Hack

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/13/2008 ↓

How to Only Retrieve Posts With Custom Fields 23comments

Author: Ronald Huereca Category: HOW-TO, WordPress, WordPress Hack

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 32comments

Author: Ronald Huereca Category: HOW-TO, WordPress Hack

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/12/2008 ↓

Shortcode Generator 1comment

Julien of Webinventif has created a shortcode generator for WordPress. Shortcode is like BBcode in that it provides the ability to use shortcuts to execute a block of code, rather than having to write out the block of code time and time again. Julien has made use of the new API calls within WordPress and with his shortcode generator, makes it easy as 1,2,3 to create your own custom shortcode. Although everything has been written in French, this generator looks promising. If anyone could translate this generator into English, I think there would be many WordPresser’s who would be grateful.

Here is a screencast showcasing the generator in action.


Shortcode generator from WebInventif.fr on Vimeo

3/8/2008 ↓

Managing Trackbacks and Pingbacks in Your WordPress Theme 34comments

With all of the recent discussion regarding trackbacks and pingbacks on Weblog Tools Collection, I thought I’d mention several ways one can deal with trackbacks and pingbacks in the context of a WordPress theme.

The topics I will be covering in this article are on separating trackbacks/pingbacks from regular comments, and also how to remove trackbacks and pingbacks from a WordPress theme completely.

Separating Trackbacks/Pingbacks From Comments

I know what you’re thinking: numerous posts have already been written on how to separate trackbacks from comments.

But what I present here is an actual separation using the “functions.php” feature for WordPress themes along with the regular “comments.php“. Both should be located in your theme directory.

theme_setup.jpg
Figure 1: Theme Directory Setup

Modifying the functions.php File

The “functions.php” file is a lifesaver for any theme developer or tinkerer wishing to add custom code or functions to themes. The code in the “functions.php” file can be called from all theme files, and can act as makeshift WordPress plugins (without the need for activation).

What we’ll be doing here is adding four functions and two filters into the file.

You don’t really have to understand the functions, but here are some brief explanations:

functions_php.jpg
Figure 2: functions.php Filter and Function Additions

  • filterPostComments: Updates the comments number for all posts so that trackbacks aren’t included in the count.
  • filterComments: Separates the trackbacks from the comments as global variables.
  • stripTrackback: Strips trackbacks from an array.
  • stripComment: Strips comments from an array.

The two filters we add in are explained below:

  • comments_array: Basically the comments before they are read in the comments loop.
  • the_posts: An array of all found posts.

Ok, enough with the explanations. Here’s the code for the “functions.php” file:

add_filter('comments_array', 'filterComments', 0);
add_filter('the_posts', 'filterPostComments', 0);
//Updates the comment number for posts with trackbacks
function filterPostComments($posts) {
	foreach ($posts as $key => $p) {
		if ($p->comment_count <= 0) { return $posts; }
		$comments = get_approved_comments((int)$p->ID);
		$comments = array_filter($comments, "stripTrackback");
		$posts[$key]->comment_count = sizeof($comments);
	}
	return $posts;
}
//Updates the count for comments and trackbacks
function filterComments($comms) {
global $comments, $trackbacks;
	$comments = array_filter($comms,”stripTrackback”);
	$trackbacks = array_filter($comms, “stripComment”);
	return $comments;
}
//Strips out trackbacks/pingbacks
function stripTrackback($var) {
	if ($var->comment_type == ‘trackback’ || $var->comment_type == ‘pingback’) { return false; }
	return true;
}
//Strips out comments
function stripComment($var) {
	if ($var->comment_type != ‘trackback’ && $var->comment_type != ‘pingback’) { return false; }
	return true;
}

Do you need to know how it works? Not really. But in summary, it separates comments from trackbacks and updates the comment count for all posts.

Modifying the comments.php file

Unlike most separation tutorials, we will not be modifying the comments loop.

In essence, we are expanding on a previous tutorial that also uses the “functions.php” file for separation of trackbacks and comments.

What we’ll be doing is the following:

  • Adding a “trackbacks” global variable right after the comments loop.
  • Initiating a trackbacks/pingbacks loop.

comments_php.jpg
Figure 3: comments.php Load Order

Right after the comments loop ends, you would add the following:

<?php global $trackbacks; ?>
<?php if ($trackbacks) : ?>
<?php $comments = $trackbacks; ?>
<h3 id="trackbacks"><?php echo sizeof($trackbacks); ?> Trackbacks/Pingbacks</h3>
	<ol class="commentlist">
	<?php foreach ($comments as $comment) : ?>
<!-- Your trackback HTML -->
<?php endforeach; /* end for each comment */ ?>
	</ol>
<?php endif; ?>

The code looks just like the comments loop except for a few lines of code, and the best part is, no editing of the original comments loop was necessary.

Download the Code

Here is a downloadable copy of the code presented in this post. The files within this zip file are:

  • Sample “functions.php” file.
  • Sample “comments.php” file.

I realize this solution is not the simplest demonstration of comment/trackback separation, but it allows for two actual and separate loops, and also produces a valid comments number(comments with trackbacks/pingbacks subtracted out) for all posts.

Removing Trackbacks/Pingbacks from WordPress Themes - Three Ways

When I asked the readers here if trackbacks were still useful, several expressed that they would be willing to remove trackbacks/pingbacks from comments.

With WordPress, I have found three ways to remove trackbacks and pingbacks from a WordPress theme.

Method 1: Edit the comments.php File

Located in almost every theme directory is a file called “comments.php“. Within this file is what’s known as the Comments Loop, which is what displays all of the comments for a post.

The start of Comments Loop looks like this:

<?php foreach ($comments as $comment) : ?>

To remove trackbacks/pingbacks from your theme, simply insert this code in the line right after the start of the loop:

<?php if ($comment->comment_type == "pingback" || $comment->comment_type == "trackback") { continue; } ?>

The above code skips over the trackbacks and pingbacks. The disadvantage of this method is that WordPress will still display the number of comments with trackbacks and pingbacks in the count.

trackbacks_comments.jpeg
Figure 4: Comments count with trackbacks included in the count

Method 2: Edit the functions.php File

Most themes should already come with a file named “functions.php“. If not, you can easily create one using any text editor.

Any code or functions in your “functions.php” file is immediately accessible by all of your theme files. The benefit of removing trackbacks/pingbacks using this technique is that you won’t have to modify any of the core template files and risk messing up your theme.

Within the functions.php file, insert this code:

add_filter('comments_array', 'filterTrackbacks', 0);
add_filter('the_posts', 'filterPostComments', 0);
//Updates the comment number for posts with trackbacks
function filterPostComments($posts) {
	foreach ($posts as $key => $p) {
		if ($p->comment_count <= 0) { return $posts; }
		$comments = get_approved_comments((int)$p->ID);
		$comments = array_filter($comments, "stripTrackback");
		$posts[$key]->comment_count = sizeof($comments);
	}
	return $posts;
}
//Updates the count for comments and trackbacks
function filterTrackbacks($comms) {
global $comments, $trackbacks;
	$comments = array_filter($comms,”stripTrackback”);
	return $comments;
}
//Strips out trackbacks/pingbacks
function stripTrackback($var) {
	if ($var->comment_type == ‘trackback’ || $var->comment_type == ‘pingback’) { return false; }
	return true;
}

This code is very similar to the code I used for separating trackbacks from comments.

Although not nearly as simple as the “comments.php” method, this method is more flexible and provides WordPress with an actual number of comments without the trackbacks/pingbacks being counted.

comments_wo_trackbacks.jpeg
Figure 5: Comments count without trackbacks included

Method 3: The Plugin Solution

For those not wishing to modify themes, there is always the plugin solution.

A plugin I wrote called Comment Sorter has a feature that allows a blogger to remove trackbacks/pingbacks (not permanently) from within the WordPress Administration Panel. There is absolutely no theme modification involved.

comment_sorter_admin.jpg
Figure 6: Comment Sorter Admin Interface

Using the above configuration for Comment Sorter (with the auto-include off and trackbacks disabled), one can easily remove trackbacks and pingbacks from a theme. It’s basically Method 2 in the form of a plugin.

Update for WordPress 2.5 - May 1, 2008

A reader pointed out that the comment count is incorrect on WordPress 2.5. For both techniques, you will want to exclude the filter the_posts and the function filterPostComments. Instead, use this filter and function:

add_filter('get_comments_number', 'filterCommentsNumber');
function filterCommentsNumber($count) {
	global $id;
	if (empty($id)) { return $count; }
	$comments = get_approved_comments((int)$id);
	$comments = array_filter($comments, "stripTrackback");
	return sizeof($comments);
}

Conclusion

Within this post I presented techniques on separating trackbacks/pingbacks from regular comments, and also how to remove trackbacks and pingbacks from a WordPress theme.

If you have any questions, please leave a comment and I’ll do my best to address them.

3/1/2008 ↓

WordPress as a Membership Directory 17comments

WordPress as a Membership Directory: After the recent tutorial on setting up WordPress as a Contact Manager, Chris Cagle has written up a tutorial on WP Designer on how to use WordPress as a Membership Directory. He has setup a Membership Directory for Pittsburgh Designers and uses his experience from that project to outline the steps, plugins and code required to set this up for yourself. Beside the annoying CSS bug that puts a text box in the middle of every page, the setup looks nice, highly versatile and very useful for both designers (in this case) and future clients. I really like the Members Directory and the ability to display detailed contact information and portfolio of every designer. Even the signup is automated (and modified to suit the need) and relatively painless. I am curious to know what they plan to do about possible spammers posing as designers, but thats another story.

[EDIT] Chris writes in the comments: “As for spammers - default registration for the site is subscriber, so they won’t get anywhere near the directory until they have been approved by the administrator (currently just me). Sort of in the way that if you submit your website to cssremix, you don’t get shown until John approves it.

2/6/2008 ↓

WordPress as a Contact Manager 28comments

WP Contact Manager: The versatility of WordPress continues to amaze me. Design Canopy has released a theme/set of instructions for WordPress that would allow you to run a WordPress install as a taggable, searchable contact manager that can be made into a Members Only system and display related contacts. Now mind you, it is not a stand alone theme, needs extra plugins to be downloaded and installed and they outline detailed instructions on how to set it up. However, the setup looks relatively easy and the results are definitely pretty cool. I would have liked to see a Prologue like custom posting interface for logged in users but that could be an easy add on or plugin once the thing is set up.

1/24/2008 ↓

Mobile Phone optimized WordPress 11comments

Mobile Phone Optimized WordPress: Thanks to a tip from Amit, I found a quick and painless way to optimize a WordPress blog (or any blog with a feed for that matter) for use with a mobile phone. The trick is to use Google’s excellent mobile news readers to display your blog. The resulting content is not only lightning fast, it is also well formatted and relatively easy to navigate. To see for yourself, craft the following URI in your browser.

http://www.google.com/reader/m/view/feed/[Your Feed URI]

This is the optimized mobile version of Weblog Tools Collection. Once you have the feed, just create a link on your blog for readers to follow and/or bookmark. Of note is the excellent WordPress Mobile plugin from Alex for those who like a one stop shop.

11/24/2007 ↓

  • WordPress Post Thumbnails

    Giving each WordPress post a thumbnail, and display the thumbnail on the home page: Interesting tutorial on creating thumbnails for each post on your blog and using Custom Fields to add and display them on your front page. A word of warning: the process is hand crafted and labor intensive. Think of them as SnapShots for your WordPress posts, hosted on your own blog. I think this could be a very cool plugin that automagically builds thumbnails for your posts and stores them on your blog. Then a custom function that behaves like “recent posts” could display thumbnails of your posts on the front page. I see this feature being really useful for those who post a lot of multimedia such as videos and pictures. Thanks HackWordPress [EDIT] Also, check out another Custom Fields thumbnail tutorial. (19)

11/11/2007 ↓

OS X WordPress Comment Moderation Notifier 5comments

WordPress Comment Moderation Notifier for OS X: After Matt made the post about the Windows system tray based comment moderation notifier for WordPress, Edward Dale wrote up a Python script to the same effect and used Growl to notify the user. There are instructions in the download.

10/26/2007 ↓

  • Easy Asides for WordPress

    Easy Asides for WordPress: Daniel has come up with another way to easily add “Asides” to your WordPress install. I use the category LinkyLoo (Of which this post is an example. If you are reading this is a feed reader, you are missing the effect) to the same effect. His method is WordPress 2.3 compatible and though it involves code modification, it is not very complex to implement. (8)

10/24/2007 ↓

WP Plugin: Custom Hooks for Developers 2comments

Custom Hooks for developers is mostly aimed at other plugin developers and it provides the manage_pages_columns and manage_pages_custom_column hooks, which are not present in WordPress, but have been requested often. The plugin replicates the custom column feature of the manage posts page. The new filters can can be used in the same way as the manage_posts_custom_column action and manage_posts_columns filter provided by WordPress.

The author has also written a tutorial on how to add custom columns to the manage posts screen which also applies to these hooks.

10/23/2007 ↓

TAGStention for WordPress & Dreamweaver 7comments

TAGStention for WordPress: TAGStention is NOT a WordPress plugin nor is it a guide, its a Dreamweaver extension that has helpful features for theme developers such as

  • Wizards for tags with parameters
  • Help button redirects to codex
  • Support for 90% of the tags
  • Insert basic loops (wizard)
  • Insert headers (wizard)
  • Ultimate TagWarrior tags supported (NEW)
  • Help button (NEW)
  • PayPal button at help screen (NEW)

Is supports Dreamweaver 8 and MX2004 and the author says that it might support some older versions. It is based on a CC license. Thanks to WordPress Candy for the tip.

Translate

Translate to German Translate to Spanish Translate to French Translate to Italian Translate to Portuguese Translate to Japanese Translate to Korean Translate to Russian Translate to Chinese

Latest Videos

Latest WordPress Jobs

S2