Created
December 19, 2011 16:44
-
-
Save roborourke/1497915 to your computer and use it in GitHub Desktop.
Small plugin to allow choosing of which categories are including in the main blog list.
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
<?php | |
/* | |
Plugin Name: Blog Categories | |
Description: Adds a list of checkboxes on the reading settings page to explicitly set which categories show up in the main blog listing. | |
Version: 0.1 | |
Author: Robert O'Rourke | |
License: GPLv2 or later | |
*/ | |
add_action( 'admin_init', 'blog_categories' ); | |
function blog_categories() { | |
add_settings_field( 'blog_categories_id', __( 'Blog categories' ), 'blog_categories_field', 'reading' ); | |
register_setting( 'reading', 'blog_categories_id', 'save_blog_categories' ); | |
} | |
function blog_categories_field() { | |
$blog_categories = get_option( 'blog_categories' ); ?> | |
<small class="description"><?php _e( '(none selected = all categories)' ); ?></small> | |
<input type="hidden" name="blog_catgories_id" value="" /> | |
<ul class="categorychecklist" style="border:1px solid #dfdfdf;border-width:1px 0;max-height:200px;overflow:auto;"><?php | |
$cats = get_terms( 'category', array( 'hide_empty' => false ) ); | |
foreach( $cats as $cat ) { | |
$field_id = 'blog_categories_' . $cat->term_id; ?> | |
<li><label for="<?php echo $field_id; ?>"> | |
<input id="<?php echo $field_id; ?>" type="checkbox" <?php if ( $blog_categories && in_array( $cat->term_id, $blog_categories ) ) echo ' checked="checked"'; ?> name="blog_categories[]" value="<?php echo $cat->term_id; ?>" /> | |
<?php echo $cat->name; ?></label></li> | |
<?php } ?> | |
</ul> | |
<?php | |
} | |
function save_blog_categories() { | |
if ( ! current_user_can( 'manage_options' ) ) | |
return false; | |
if ( get_option( 'blog_categories' ) ) | |
update_option( 'blog_categories', $_POST[ 'blog_categories' ] ); | |
else | |
add_option( 'blog_categories', $_POST[ 'blog_categories' ] ); | |
} | |
// if its the home page and the main query then run our filter | |
add_action( 'pre_get_posts', 'blog_categories_filter' ); | |
function blog_categories_filter( $query ) { | |
global $wp_query; | |
$blog_categories = get_option( 'blog_categories' ); | |
if ( $blog_categories && $query->is_home && $query === $wp_query ) | |
$query->query_vars[ 'cat' ] = implode( ',', $blog_categories ); | |
return $query; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment