Computing Magazine

WordPress Proper Query_posts with Real Results

Posted on the 18 July 2014 by Akahgy

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.

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.


Back to Featured Articles on Logo Paperblog