Sort category at random?
-
Is there a way to sort the category randomly, since this option already exists in posts?
Has anyone had this need?
-
Using WP_Query? No, at least not through the usual query arguments. You can hack the actual SQL query string through a filter like “posts_request”, changing the supplied ORDER BY clause with one that uses ORDER BY RAND().
Since the order is random, it’s illogical to order by random category, or random authors or random anything specific. The result would still be random posts no matter what data you supposedly ordered by.
FWIW, WP_Query does not have an argument to order ASC or DESC by any category column (name, slug, ID, etc.), nor tags, nor any other taxonomy terms. Ordering can only be done by meta field items or post columns (title, date, author, etc.)
In my case it does not work, as I need the random sorting of the categories to use the category name in a new query within the posts.
In this example, I’ll be using the posts first, when I want to use the categories and the categories link that I ask the posts.
Understood?
Thanks for trying to help.So you want one randomly selected category that can then be used to query all posts in that category?
There’s no random ordering argument for any WordPress defined taxonomy query. You could query the DB directly for category terms ordered by RAND() using the $wpdb object. Or you could use a function like get_categories() to get all terms, ordered by name or whatever. Then randomly pick out one of the terms. There’s a few ways to do this. array_rand() will return a random key of an array. You can then use the key to get an array element from which you can extract the name or term ID for use in WP_Query arguments.
If you want all the terms randomly ordered, run the results array through shuffle().
Okay, now I’ll have to think of a way to store this first result in a variable and then apply array_rand () on this variable.
I’ll do my tests here !!
Thanks a lot for the help!
–
–
Using array_rand () does not work, because in get_categories I get six positions and when I use the array_rand () function, it always repeats one or more positions, I was only wanting to change the order I get, These positions changed.-
This reply was modified 9 years, 2 months ago by
GsmLobo-rio.
Thanks a lot for the help!
I found the solution that meets my need, I use the get_categories () function, loop the result, store the term_id into an array, and then use the function (http://php.net/manual/pt_BR/function.shuffle .php) from php to shuffle the result, this way I always have the same result without a single order !!!Yes, I can see now how array_rand() is the wrong approach. I had a different application in mind in suggesting that. I’m glad you figured out how to get shuffle() to meet your needs 🙂
-
This reply was modified 9 years, 2 months ago by
The topic ‘Sort category at random?’ is closed to new replies.