Voulez-vous afficher les articles dans un ordre aléatoire tout en conservant l’ordre de pagination ? Ce snippet vous permettra d’afficher une liste aléatoire d’articles qui resteront dans le même ordre tant que la session existera. Cela permet de s’assurer que la pagination sera cohérente.
Instructions:
Tout ce que vous avez à faire est d’ajouter ce code dans le fichier functions.php de votre thème ou dans un plugin spécifique à votre site:
session_start(); add_filter( 'posts_orderby', 'randomise_with_pagination' ); function randomise_with_pagination( $orderby ) { if( is_front_page() ) { // Reset seed on load of initial archive page if( ! get_query_var( 'paged' ) || get_query_var( 'paged' ) == 0 || get_query_var( 'paged' ) == 1 ) { if( isset( $_SESSION['seed'] ) ) { unset( $_SESSION['seed'] ); } } // Get seed from session variable if it exists $seed = false; if( isset( $_SESSION['seed'] ) ) { $seed = $_SESSION['seed']; } // Set new seed if none exists if ( ! $seed ) { $seed = rand(); $_SESSION['seed'] = $seed; } // Update ORDER BY clause to use seed $orderby = 'RAND(' . $seed . ')'; } return $orderby; }
Note : Si c’est la première fois que vous ajoutez des extraits de code dans WordPress, veuillez vous référer à notre guide sur comment copier/coller correctement des extraits de code dans WordPress, afin de ne pas casser accidentellement votre site.
Si vous avez aimé cet extrait de code, n’hésitez pas à consulter nos autres articles sur le site comme : 7 meilleurs constructeurs de pages WordPress comparés.
Thank you!
It works like a charm…. but it creates 9 additional post-pages at the end, landing to “404 Page Not Found”
Any thoughts?
Thank you in advance.
Josh
Thank You! it works like a charm… but How about when using a Cache plugin?… I’ve purged all cache and still it doesn’t work in first page only.
Any thoughts is appreciated.
Thanks once again.
Josh.
exactly what I was looking for, thank you!!
Hi, this code works very well. The only problem is that in the front page it also shows the “recent post” widget in randon order. Some idea how to change that?
I didn’t notice it until you mentioned it but we have exactly the same problem, glad you pointed it out.
Did you manage to solve it somehow?
I put in the snippet using the snippet plugin. I am just setting up this site locally and only have 4 test posts. I do not notice the posts randomizing….at what point does the randomize happen?
THANK YOU!!
THANK YOU SO MUCH!!! YOU HELPED ME SO MUCH!!!
Glad the snippet was helpful
Is this supposed to fix the ‘second page random posts’ issue? Or is it to illustrate the issue? I’ve used it to generate some randomly ordered posts, but when I go to the second page, the randomisation obviously starts again, because I may or may not get the same posts appearing.
Thanks a lot. I had been looking for code like this to share more articles with the rrader at the end of my site.