Created
August 5, 2014 12:11
-
-
Save fredbradley/a5e6c1a23d3aa23fa79e to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Update Custom Terms | |
* | |
* @author Fred Bradley <@fredbradley> | |
* @version 1.0 | |
* @since Since Release 1.0.0 | |
*/ | |
function update_station_tag_list($post_id) { | |
// only update terms if it's a post-type-B post | |
if ( 'station' != get_post_type($post_id)) { | |
return; | |
} | |
// don't create or update terms for system generated posts | |
if (get_post_status($post_id) == 'auto-draft') { | |
return; | |
} | |
/* | |
* Grab the post title and slug to use as the new | |
* or updated term name and slug | |
*/ | |
$term_title = get_the_title($post_id); | |
$term_slug = get_post( $post_id )->post_name; | |
$debug = wp_set_post_terms( $post_id, $term_title, 'post_tag', true ); | |
if ( is_wp_error( $debug ) ) { | |
$error_string = $debug->get_error_message(); | |
return '<div id="message" class="error"><p>' . $error_string . '</p></div>'; | |
} | |
/* | |
* Check if a corresponding term already exists by comparing | |
* the post ID to all existing term descriptions. | |
*/ | |
$existing_terms = get_terms('post_tag', array( | |
'hide_empty' => false | |
) | |
); | |
foreach($existing_terms as $term) { | |
if ($term->description == $post_id) { | |
//term already exists, so update it and we're done | |
wp_update_term($term->term_id, 'post_tag', array( | |
'name' => $term_title, | |
'slug' => $term_slug | |
) | |
); | |
return; | |
} | |
} | |
/* | |
* If we didn't find a match above, this is a new post, | |
* so create a new term. | |
*/ | |
wp_insert_term($term_title, 'post_tag', array( | |
'slug' => $term_slug, | |
'description' => $post_id | |
) | |
); | |
} | |
//run the update function whenever a post is created or edited | |
add_action('save_post', 'update_station_tag_list'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment