certainlyakey
1/20/2015 - 8:07 PM

Wordpress - set default terms in custom taxonomies

Wordpress - set default terms in custom taxonomies

/**
 * Define default terms for custom taxonomies in WordPress
 *
 * @author    Michael Fields     http://wordpress.mfields.org/
 * @props     John P. Bloch      http://www.johnpbloch.com/
 * @props     Evan Mulins        http://circlecube.com/2013/01/set-default-terms-for-your-custom-taxonomy-default/
 *
 * @since     2010-09-13
 * @alter     2013-01-31
 *
 * @license   GPLv2
 */
function mfields_set_default_object_terms( $post_id, $post ) {
	if ( 'publish' === $post->post_status && $post->post_type === 'your_custom_post_type' ) {
		$defaults = array(
			'your_taxonomy_id' => array( 'your_term_slug' )
			);
		$taxonomies = get_object_taxonomies( $post->post_type );
		foreach ( (array) $taxonomies as $taxonomy ) {
			$terms = wp_get_post_terms( $post_id, $taxonomy );
			if ( empty( $terms ) && array_key_exists( $taxonomy, $defaults ) ) {
				wp_set_object_terms( $post_id, $defaults[$taxonomy], $taxonomy );
			}
		}
	}
}
add_action( 'save_post', 'mfields_set_default_object_terms', 100, 2 );