Skip to content

Instantly share code, notes, and snippets.

@rezzz-dev
Last active January 20, 2016 14:35
Show Gist options
  • Save rezzz-dev/ba603f184ce305ad0a6f to your computer and use it in GitHub Desktop.
Save rezzz-dev/ba603f184ce305ad0a6f to your computer and use it in GitHub Desktop.
Filter Recent Posts Widget by current categories, but excluding current post
<?php
/*
* Filter Recent Posts based around the categories of the post being displayed
*/
function rez_widget_posts_args( $args ) {
if ( is_single() ) { // Only want to appear on blog posts.
$post = get_queried_object();
$categories = wp_get_post_categories( $post->ID );
$cats = implode( ',',$categories );
return array(
'posts_per_page' => $args['posts_per_page'], // The number from the widget settings.
'no_found_rows' => true,
'post_status' => 'publish',
'ignore_sticky_posts' => true,
'cat' => $cats, // The current categories.
'post__not_in' => array( $post->ID ) // Remove the current post as well.
);
} else { // Keeps the normal behavior if we are not in category context.
return $args;
}
}
add_filter( 'widget_posts_args', 'rez_widget_posts_args' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment