Navigation
This is archived content. Visit our new forum.

Tagged: 

  • Author
    Posts
  • #1152230
    necxelos
    Participant

    Hello

    I made myself roughly 50 fake posts of content for testing purposes (with tags, categories, lorem-ipsum-generated text, different shortcodes used, etc.) but I was sloppy enough to have them in very specific order (all from one category, then all from the other etc.).

    To be able to test how different-styled posts look next to each other I needed a way to order them randomly. I found this piece of code:

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

    Which does exactly what I need but only on the blog page (AKA all posts page). Can You guys help me modify this code to make posts ordered randomly on category-archive pages too (by that I mean inside X category archive there are still only posts from X category but ordered randomly, and inside Y category archive there are still only posts from Y category but ordered randomly, etc.)?

    Thanks in advance and good day to You all 🙂

    #1152764
    Lely
    Moderator

    Hi There,

    Thanks for posting in.
    From your code, please update this line:
    if( is_front_page() ) { => This code refers to blog index page
    To this:
    if( is_front_page() || is_category()) { => This code means blog index page or category page
    In case you want to be specific, please update to this:
    if( is_front_page() || is_category(1) || is_category(2)) { =>This code means blog index page or specific category page
    Replace 1 and 2 with your own category ID.
    This link might help:https://developer.wordpress.org/reference/functions/is_category/

    #1153412
    necxelos
    Participant

    Works like a charm, without any visible issues as far as I can tell 🙂

    Thank You Lely 🙂

    #1153512
    Joao
    Moderator

    Glad to hear it,

    Let us know if you need help with anything else.

    Joao

  • <script> jQuery(function($){ $("#no-reply-1152230 .bbp-template-notice, .bbp-no-topic .bbp-template-notice").removeClass('bbp-template-notice'); }); </script>