X

Cómo mostrar mensajes en un orden aleatorio y mantener el orden de paginación

Snippets by IsItWP

¿Quieres mostrar las entradas en un orden aleatorio manteniendo el orden de paginación? Este fragmento le permitirá mostrar una lista aleatoria de entradas aleatorias que permanecerán en el mismo orden mientras exista la sesión. Esto asegura que la paginación será consistente.

Instrucciones:

Todo lo que tienes que hacer es añadir este código al archivo functions.php de tu tema o en un plugin específico del sitio:


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;
}

Nota: Si es la primera vez que añade fragmentos de código en WordPress, consulte nuestra guía sobre cómo copiar / pegar correctamente fragmentos de código en WordPress, para no romper accidentalmente su sitio.

Si te ha gustado este fragmento de código, por favor, considere revisar nuestros otros artículos en el sitio como: 7 mejores constructores de páginas de WordPress de arrastrar y soltar comparados.

Comentarios   Deja una respuesta

  1. 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

  2. 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.

  3. exactly what I was looking for, thank you!!

  4. 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?

    1. 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?

  5. 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?

  6. Riccardo Vezzani junio 18, 2019 en 12:17 pm

    THANK YOU!!

  7. THANK YOU SO MUCH!!! YOU HELPED ME SO MUCH!!!

    1. Glad the snippet was helpful

  8. 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.

  9. Thanks a lot. I had been looking for code like this to share more articles with the rrader at the end of my site.

Añadir un comentario

Nos alegra que haya decidido dejar un comentario. Tenga en cuenta que todos los comentarios se moderan de acuerdo con nuestra política de privacidad , y que todos los enlaces son nofollow. NO utilice palabras clave en el campo del nombre. Tengamos una conversación personal y significativa.

WordPress Launch Checklist

La lista definitiva para lanzar WordPress

Hemos recopilado todos los elementos esenciales de la lista de comprobación para el lanzamiento de su próximo sitio web de WordPress en un práctico ebook.
Sí, envíeme el ¡gratuito!