Created
March 15, 2020 09:56
-
-
Save kaoru-fukusato/0a6ff0f27d9ced7ca15cb7f5916479e9 to your computer and use it in GitHub Desktop.
記事ランダム①
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function category_rand_orderby( $orderby, $query ){ | |
if ( !is_admin() && $query->is_main_query() ) { | |
if ( $query->is_category() ) { | |
$seed = strtotime( date( 'Y-m-d H:00:00' ) ); | |
mt_srand( $seed ); | |
$orderby = 'RAND(' . mt_rand() . ')'; | |
} | |
} | |
remove_filter( current_filter(), __FUNCTION__ ); | |
return $orderby; | |
} | |
add_filter( 'posts_orderby', 'category_rand_orderby', 10, 2 ); | |
----------------- | |
function fix_rand_orderby( $orderby, $query ){ | |
if ( 'rand' == $query->get( 'orderby' ) ) { | |
$seed = strtotime( date( 'Y-m-d H:00:00' ) ); | |
mt_srand( $seed ); | |
$orderby = 'RAND(' . mt_rand() . ')'; | |
} | |
return $orderby; | |
} | |
add_filter( 'posts_orderby', 'fix_rand_orderby', 10, 2 ); | |
--------------------- | |
function category_rand_pre_get_posts( $query ) { | |
if ( is_admin() || !$query->is_main_query() ) | |
return; | |
if ( $query->is_category() ) | |
$query->set( 'orderby', 'rand' ); | |
} | |
add_action( 'pre_get_posts', 'category_rand_pre_get_posts' ); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment