Created
March 6, 2020 18:20
-
-
Save brunolimadevelopment/cfab3f08b81324c2f3b3ae282e576a01 to your computer and use it in GitHub Desktop.
WP_Query [ SHUFFLE ] - 1 postagem aleatória das 5 últimas
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
// ADC NO ARQUIVO functions.php | |
//SHURFFLE NAS QUERYS DAS POSTAGENS | |
add_filter( 'the_posts', function( $posts, \WP_Query $query ){ | |
if( $pick = $query->get( '_shuffle_and_pick' ) ) { | |
shuffle( $posts ); | |
$posts = array_slice( $posts, 0, (int) $pick ); | |
} | |
return $posts; | |
}, 10, 2 ); | |
// OU ESSE DE BAIXO | |
function wpse260713_randomize_posts( $sql_query, $query ) { | |
$rand = (int) $query->get( '_randomize_posts_count' ); | |
if( $rand ) { | |
$found_rows = ''; | |
if( stripos( $sql_query, 'SQL_CALC_FOUND_ROWS' ) !== FALSE ) { | |
$found_rows = 'SQL_CALC_FOUND_ROWS'; | |
$sql_query = str_replace( 'SQL_CALC_FOUND_ROWS ', '', $sql_query ); | |
} | |
$sql_query = sprintf( 'SELECT %s wp2__posts.* from ( %s ) wp2__posts ORDER BY rand() LIMIT %d', $found_rows, $sql_query, $rand ); | |
} | |
return $sql_query; | |
} | |
add_filter( 'posts_request', 'wpse260713_randomize_posts', 10, 2 ); | |
// ARGUMENTOS PARA O WP_QUERY | |
$args = array( | |
'post_type' => 'post', | |
'cat' => '3,6', // ID da categoria. | |
'category__not_in' => array(8, 5), | |
'meta_key' => 'news_destaque', | |
'meta_value' => '1', | |
'posts_per_page' => 5, // É RETORNADO 5 POSTS | |
'no_found_rows' => 'true', | |
'_shuffle_and_pick'=>1, // EXIBE 1 POST POR VEZ DOS 5, ALTERNANDO RAMDOMICAMENTE. | |
//'_randomize_posts_count' => 1 // wpse260713_randomize_posts() | |
'orderby' => 'date', | |
'order' => 'DESC' | |
); | |
// https://911wordpress.info/questions/2497/wp-query-receba-3-postagens-aleatorias-das-10-ultimas |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment