/*
Plugin Name: Single Postag
Description: Enforces use of single 'post_tag' taxonomy on select posts.
Author: EarnestoDev
Version: 1.0.0
Author URI: http://www.earnestodev.com/
*/
// Prepare to save new post_tag
add_action('wp_insert_post', function postag_wp_insert_post($post_ID, $post){
// Don't update if field value was not posted
if(!isset($_POST['single_postag'])) return;
// Fix WP slashing madness (I hate this joke)
$postag = stripslashes(trim($_POST['single_postag']));
$postag = $postag ? array(trim($postag)) : array();
// Set object terms, don't append
wp_set_object_terms($post_ID, $postag, 'post_tag', false);
}
add_action('wp_insert_post', 'postag_wp_insert_post', 10, 2); // 2 args required
// And now hijack theThe metaxbox
add_action('add_meta_boxes', function($post_type, $post){
// Discard default 'post_tag' metabox (Important)
remove_meta_box('tagsdiv-post_tag', $post_type, 'side');
// Only add the new metabox if post_type supports 'post_tag' taxonomy
if(!is_object_in_taxonomy($post_type, 'post_tag')) return;
// Create a new 'tagsdiv-postag' metabox (you can't reuse the old MBis name)here
add_meta_box('tagsdiv-postag', __('Tag'), function postag_meta_box($post, $box){
// Get the tags and only keep names to weld
$tags = wp_get_post_tags($post->ID);
// Loop through as references for quick value reassignment
foreach($tags as &$tag) $tag = $tag->name;
// If multiple tags are added outside this widget, they are combined on save.
echo '<p><input type="text" class="widefat" name="single_postag" value="',
esc_attr(implode(', ', $tags)), '" /></p>';
// Pimp description so your users can understand this
echo '<p class="description">', 'Enter a single Tag.', '</p>';
}
// And now hijack }the metaxbox
function postag_add_meta_boxes($post_type, $post){
// Discard default 'post_tag' metabox (Important)
remove_meta_box('tagsdiv-post_tag', $post_type, 'side');
// Only add the new metabox if post_type supports 'post_tag' taxonomy
if(!is_object_in_taxonomy($post_type, 'post_tag')) return;
// Create a new 'tagsdiv-postag' metabox (you can't reuse the old MB name)
add_meta_box('tagsdiv-postag', __('Tag'), 'postag_meta_box',
$post_type, 'side', 'core');
}
add_action('add_meta_boxes', 'postag_add_meta_boxes', 10, 2); // 2 args required