[wp-hackers] Extending query_posts?

Sam Angove sam at rephrase.net
Sun Jan 29 11:56:22 GMT 2006


On 1/29/06, Mattias Winther <mattias at winthernet.se> wrote:
>
> 1. Are there any other approaches that might work better? I realize there are ways to do a hack that does this, but I really want to make it feel like it was integrated in the wordpress core.
> 2. Is there a hook for looking at and modifying the query just before sending it to the SQL server?

2. There's a bunch of them. posts_where, posts_join, posts_orderby
etc. Browse WP_Query::get_posts() in classes.php.

1. I don't know how fast it is, but you can do it with ORDER BY RAND().

This seems to work:

<?php
/*
Plugin Name: Random Posts
*/

function query_random_posts($query) {
	return query_posts($query . '&random=true');	
}

class RandomPosts {
	function orderby($orderby) {
		if ( get_query_var('random') == 'true' )
			return "RAND()";
		else
			return $orderby;
	}
	function register_query_var($vars) {
		$vars[] = 'random';
		return $vars;
	}
}
add_filter( 'posts_orderby', array('RandomPosts', 'orderby') );
add_filter( 'query_vars', array('RandomPosts', 'register_query_var') );
?>


More information about the wp-hackers mailing list