[wp-hackers] How to display random post with next and previous links alphetically showed
Deepak Mittal
dpac.mittal2 at gmail.com
Tue Jul 12 21:34:57 UTC 2011
I solved the issue by creating custom_field with 'title' key and just
copying same title. This is because I could use comparison operators on
meta-values in WP_QUERY. My code looked something like this:
In index.php above the loop:
query_posts(array('orderby'=>'rand', 'posts_per_page'=>1));
In functions.php:
function next_prev_links ($title){
wp_reset_query();
$next_query = new WP_Query( array( 'orderby' => 'title', 'order' => 'ASC',
'posts_per_page' => 1, 'meta_key' => 'title', 'meta_value' => $title,
'meta_compare' => '>' ) );
wp_reset_query();
$prev_query = new WP_Query( array( 'orderby' => 'title', 'order' => 'DESC',
'posts_per_page' => 1, 'meta_key' => 'title', 'meta_value' => $title,
'meta_compare' => '<' ) );
/*
echo permalinks here....
*/
}
This gave me objects for the next and previous links and used them for
displaying the links.
Although this uses 3 SQL queries, I thought it was a much cleaner solution
than sorting an array of random posts (which might contain 100s of posts),
then looping through them to find next and previous posts.
Thanks for all the help :)
On Wed, Jul 13, 2011 at 2:49 AM, Claude Needham <gxxaxx at gmail.com> wrote:
> On Tue, Jul 12, 2011 at 11:44 AM, Otto <otto at ottodestruct.com> wrote:
> > Ahh, yes. Of course that doesn't work. SQL doesn't work that way.
> > Well, the only thing I can think of is to sort the $wp_query->posts
> > manually after getting the random list.
>
> It might help that you don't have to fully sort the list.
> All that should be required is to traverse the list looking for the
> post that is less than the rand post but greater than any other post
> which is also less. In addition find any post that is greater than the
> rand post but less than all other posts which are greater.
>
> So a single loop through the titles should give you want you need.
>
> Regards,
> Claude
> _______________________________________________
> wp-hackers mailing list
> wp-hackers at lists.automattic.com
> http://lists.automattic.com/mailman/listinfo/wp-hackers
>
--
Regards,
Deepak Mittal,
Twitter - @dpacmittal
More information about the wp-hackers
mailing list