Created
December 11, 2020 16:59
-
-
Save swinggraphics/ee621e9fb8a516c8ca9ed98fbf257bbc to your computer and use it in GitHub Desktop.
Exclude posts that have been displayed already by setting `avoid_duplicates` query var
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
// Based on code from https://ashton.codes/avoid-showing-wordpress-post-multiple-loops/ | |
function sg_track_displayed_posts( $permalink, $post ) { | |
global $sg_displayed_posts; | |
$sg_displayed_posts[ $post->post_type ][] = get_the_ID(); | |
return $permalink; | |
} | |
add_filter( 'post_link', 'sg_track_displayed_posts', 10, 2 ); | |
add_filter( 'post_type_link', 'sg_track_displayed_posts', 10, 2 ); | |
function sg_remove_already_displayed_posts( $query ) { | |
global $sg_displayed_posts; | |
if ( | |
(bool) $query->get( 'avoid_duplicates' ) | |
&& isset( $sg_displayed_posts[ $query->get( 'post_type' ) ] ) | |
) { | |
$query->set( 'post__not_in', $sg_displayed_posts[ $query->get( 'post_type' ) ] ); | |
} | |
} | |
add_action( 'pre_get_posts','sg_remove_already_displayed_posts' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment