WordPress proper query_posts with real results

Description:

WordPress query_posts() function is pretty powerful, and easy to read out. However, you need to know what you’re querying for, as very often the results are not the expected ones. The specific post meta query is covered here.

Solution:

Take care of pagination. For regular queries, you don’t need that impediment, and somehow WordPress does it on it’s own. How to avoid it? Add a huge number of posts_per_page to the arguments array:

$args[‘posts_per_page’ ] = 99999;

You need to exclude tags fast, based only on the slug? Nothing simpler:

$args[‘tag__not_in’] = array(get_term_by(‘slug’, TAG_1, ‘post_tag’)->term_id, get_term_by(‘slug’, TAG_2, ‘post_tag’)->term_id, get_term_by(‘slug’, TAG_3, ‘post_tag’)->term_id);

You can find out an id of a term very easy like this. Works as well for categories:

$categoryId = get_term_by(‘slug’, CATEGORY_SLUG, ‘category’)->term_id;

You can calculate the number of valid posts you are actually displaying by your rules by combining the arguments:

$args=array(
‘tag__not_in’ => array(get_term_by(‘slug’, TAG_1,      ‘post_tag’)->term_id, get_term_by(‘slug’, TAG_2, ‘post_tag’)->term_id),
‘post_type’ => ‘post’,
‘post_status’ => ‘publish’,
‘category_name’ => CATEGORY_SLUG,
‘posts_per_page’ => 99999,
);

$nrOfPostsInCategory = count(query_posts($args));

This actually returns the number of published posts in a category, without the ones that have the excluded tags. This comes in useful when you want to use functional tags, that aid your code or they way you use some posts.

Advertisements

About admin

Just another php developer trying to give something back to the community.
This entry was posted in Wordpress and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s