Community Forums › Forums › Archived Forums › Design Tips and Tricks › Category Template Sort Order
Tagged: pre_get_posts, random order
- This topic has 8 replies, 2 voices, and was last updated 9 years ago by
deejuk.
-
AuthorPosts
-
May 30, 2017 at 9:39 am #207156
deejuk
MemberHi all.
Can anyone please tell me what piece of code I need to add to a category template to sort the posts in a random order.
All I have in my current category template is :-
<?php
/**
* Genesis Framework.
*
* WARNING: This file is part of the core Genesis Framework. DO NOT edit this file under any circumstances.
* Please do all modifications in the form of a child theme.
*
* @package Genesis\Templates
* @author StudioPress
* @license GPL-2.0+
* @link http://my.studiopress.com/themes/genesis/
*///* Move featured image above post title in archives
remove_action( 'genesis_entry_content', 'genesis_do_post_image', 8 );
add_action( 'genesis_entry_header', 'genesis_do_post_image', 8 );genesis();
http://localMay 30, 2017 at 10:39 pm #207194Brad Dalton
ParticipantMay 31, 2017 at 3:27 am #207199deejuk
MemberHi Brad thanks for that but how do I write it into the function for the category template
May 31, 2017 at 3:46 am #207200Brad Dalton
ParticipantMay 31, 2017 at 5:24 am #207204deejuk
MemberHi Brad thanks again .. sorry I'm no good at code. I'll leave it thanks for your pointers
May 31, 2017 at 5:45 am #207207Brad Dalton
Participantdeejuk
If you search for pre_get_posts you'll find code like this
You can then add a conditional tag after the function to control where the code executes.
Some effort is required at your end..
May 31, 2017 at 7:29 am #207216deejuk
MemberHi ... thanks for the lead on this I have worked it out now with your help.
I tired the following code in my category-4.php template
add_action( 'pre_get_posts', 'generate_random_category_posts');
function generate_random_category_posts( $query ) {
if ( $query->is_category()) {
$query->set( 'orderby', 'rand' );
}
}It didn't work ...
So I put this in my functions.php
add_action( 'pre_get_posts', 'generate_random_category_posts');
function generate_random_category_posts( $query ) {
if ( $query->is_category(4)) {
$query->set( 'orderby', 'rand' );
}
}And it worked. Plus the blog area remains sorted chronologoically.
Can't work out why it didn't work in category-4.php but at least it's working now ... really need to get my head around all of this but thank you Brad once again
May 31, 2017 at 7:49 am #207217Brad Dalton
ParticipantThis is what i would use:
add_action( 'pre_get_posts', 'generate_random_category_posts'); function generate_random_category_posts( $query ) { if ( $query->is_main_query() && !is_admin() && $query->is_category('4') ) { $query->set( 'orderby', 'rand' ); } }
May 31, 2017 at 11:36 am #207228deejuk
MemberHi Brad - you're smarter than me for certain.. I need to study more
-
AuthorPosts
- The forum ‘Design Tips and Tricks’ is closed to new topics and replies.