Skip to content

Instantly share code, notes, and snippets.

@roborourke
Created December 19, 2011 17:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roborourke/1497997 to your computer and use it in GitHub Desktop.
Save roborourke/1497997 to your computer and use it in GitHub Desktop.
This plugin lets you exclude categories from the standard blog posts query in WordPress
<?php
/*
Plugin Name: Exclude Categories
Description: Adds a list of checkboxes on the reading settings page to explicitly exclude categories from the main blog listing.
Version: 0.1
Author: Robert O'Rourke
License: GPLv2 or later
*/
add_action( 'admin_init', 'exclude_categories' );
function exclude_categories() {
add_settings_field( 'exclude_categories_id', __( 'Exclude categories from main blog' ), 'exclude_categories_field', 'reading' );
register_setting( 'reading', 'exclude_categories_id', 'save_exclude_categories' );
}
function exclude_categories_field() {
$exclude_categories = get_option( 'exclude_categories' ); ?>
<input type="hidden" name="exclude_categories_id" value="" />
<ul class="categorychecklist" style="max-height:220px;overflow:auto;"><?php
$cats = get_terms( 'category', array( 'hide_empty' => false ) );
foreach( $cats as $cat ) {
$field_id = 'exclude_categories_' . $cat->term_id; ?>
<li><label for="<?php echo $field_id; ?>">
<input id="<?php echo $field_id; ?>" type="checkbox" <?php if ( $exclude_categories && in_array( "-{$cat->term_id}", $exclude_categories ) ) echo ' checked="checked"'; ?> name="exclude_categories[]" value="-<?php echo $cat->term_id; ?>" />
<?php echo $cat->name; ?></label></li>
<?php } ?>
</ul>
<?php
}
function save_exclude_categories() {
if ( ! current_user_can( 'manage_options' ) )
return false;
if ( get_option( 'exclude_categories' ) )
update_option( 'exclude_categories', $_POST[ 'exclude_categories' ] );
else
add_option( 'exclude_categories', $_POST[ 'exclude_categories' ] );
}
// if it's the home page and the main query then run our filter
add_action( 'pre_get_posts', 'exclude_categories_filter' );
function exclude_categories_filter( $query ) {
global $wp_query;
$exclude_categories = get_option( 'exclude_categories' );
if ( $exclude_categories && $query->is_home && $query === $wp_query )
$query->query_vars[ 'cat' ] = implode( ',', $exclude_categories );
return $query;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment