Created
November 28, 2012 13:08
-
-
Save caratage/4161177 to your computer and use it in GitHub Desktop.
Variants of query_posts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://www.binarymoon.co.uk/2010/03/5-wordpress-queryposts-tips/ | |
<?php | |
$query = 'posts_per_page=10'; | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
if ($queryObject->have_posts()) { | |
while ($queryObject->have_posts()) { | |
$queryObject->the_post(); | |
the_title(); | |
the_content(); | |
} | |
} | |
?> | |
<?php | |
// GOOD | |
// select 10 posts from category 1 | |
$query = 'posts_per_page=10&cat=1'; | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
// BETTER | |
$query = array ( | |
'posts_per_page' => 10, | |
'cat' => 1 | |
); | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
?> | |
<?php | |
// select posts ordered by comment_count | |
$query = 'orderby=comment_count'; | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
?> | |
<?php | |
// grab posts by post count ordered in descending order (most votes first) | |
$query = 'meta_key=vote_count&orderby=meta_value&order=DESC'; | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
?> | |
<?php | |
// grab 1 random attachment | |
$query = 'post_type=attachment&orderby=rand&posts_per_page=1'; | |
$queryObject = new WP_Query($query); | |
// The Loop... | |
?> | |
$bmIgnorePosts = array(); | |
/** | |
* add a post id to the ignore list for future query_posts | |
*/ | |
function bm_ignorePost ($id) { | |
if (!is_page()) { | |
global $bmIgnorePosts; | |
$bmIgnorePosts[] = $id; | |
} | |
} | |
/** | |
* reset the ignore list | |
*/ | |
function bm_ignorePostReset () { | |
global $bmIgnorePosts; | |
$bmIgnorePosts = array(); | |
} | |
/** | |
* remove the posts from query_posts | |
*/ | |
function bm_postStrip ($where) { | |
global $bmIgnorePosts, $wpdb; | |
if (count($bmIgnorePosts) > 0) { | |
$where .= ' AND ' . $wpdb->posts . '.ID NOT IN(' . implode (',', $bmIgnorePosts) . ') '; | |
} | |
return $where; | |
} | |
add_filter ('posts_where', 'bm_postStrip'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment