Created
July 28, 2012 06:22
-
-
Save evansolomon/3192076 to your computer and use it in GitHub Desktop.
WordPress: Only allow one post in a category at a time
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: Move Old Urgent Posts | |
*/ | |
function es_update_urgent_post_cats( $post_id ) { | |
// Get our category | |
$the_category = 'urgent'; | |
$the_category_obj = get_category_by_slug( $the_category ); | |
$the_category_id = $the_category_obj->term_id; | |
$new_category = "$the_category-archive"; // This category must exist | |
$new_category_obj = get_category_by_slug( $new_category ); | |
$new_category_id = $new_category_obj->term_id; | |
// If the post being published isn't in the category we care above, move on | |
if ( ! has_category( $the_category, $post_id ) ) | |
return; | |
// Get all posts in our category except the newest one | |
$args = array( | |
'category_name' => $the_category, | |
'orderby' => 'date', | |
'order' => 'DESC', | |
'offset' => 1, | |
); | |
$query = new WP_Query( $args ); | |
// Loop through them | |
if ( $query->have_posts() ): | |
while ( $query->have_posts() ): | |
$query->the_post(); | |
// Move any urgent posts to the archive category | |
$cats = wp_get_post_categories( $post->ID ); | |
$cats = array_diff( $cats, array( $the_category_id ) ); | |
$cats = array_values( $cats ); | |
$cats[] = $new_category_id; | |
wp_set_post_categories( $post->ID, $cats ); | |
endwhile; // have_posts() | |
endif; // have_posts() | |
// Cleanup after ourselves | |
wp_reset_postdata(); | |
} | |
add_action( 'post_publish', 'es_update_urgent_post_cats' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment