Skip to content

Instantly share code, notes, and snippets.

@ericpedia
Created September 2, 2012 01:23
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 ericpedia/3593283 to your computer and use it in GitHub Desktop.
Save ericpedia/3593283 to your computer and use it in GitHub Desktop.
WP - Add custom field and term based on title when saving a post
// Problem: This adds the term to the taxonomy, but it does not connect it to the post. It seems to connect it to the revision or something.
// Problem: When the title updates, the custom field does not update until after saving twice.
add_filter ('title_save_pre','w559_title_hook');
function w559_title_hook($title) {
global $post;
$id = get_the_id();
$pt = get_post_type();
// Check if this is the right post type
if ( $pt == 'tax' ) {
// Parse the title to see if it has a figure number and type
// Title format is "Identifier | Table 10 | Title"
$title_parts = explode('|', $title);
$title_main = array_pop($title_parts);
$title_main = trim($title_main);
$label = array_pop($title_parts);
$label = trim($label);
$type = preg_replace('/.*(Table|Figure).*/i', '$1', $label);
// $timestamp = date('h:i:s');
// If it has a figure type, save that in the type taxonomy
if ( $type ) {
$taxonomy = 'type';
// if ( ! isset( $post->post_type ) || $post->post_type != 'tax' )
// if (!wp_is_post_revision($id))
wp_set_object_terms( $id, $type, $taxonomy, $Do_Not_Overwrite_Existing_Terms = true);
}
// If it has a figure number, save it into a custom field
if ( $label ) {
$meta_key = 'chart_label';
update_post_meta( $id, $meta_key, $label );
}
}
return $title;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment