Give Custom Taxonomy’s Custom Meta Field a Default Value For All Terms

This is useful for a case in which you have created a WordPress custom taxonomy, and then you’ve added a custom meta field to it. And then you want to assign a default value to the custom meta field for all the custom taxonomy terms.

This will update all the custom taxonomy terms with a default value for its custom meta fields. This example has 2 custom meta fields, so it is updating the values for 2 custom meta fields. Replace ‘term_meta_key_1‘ and ‘term_meta_key_2‘ on lines 16 and 17 with your own custom term meta fields. Then, replace “999999” on lines 16 and 17 with your desired values to give to these custom meta fields. If you only have 1 custom meta field, then remove line 17.

The custom meta field values will be assigned to every term within your custom taxonomy. Replace your_custom_taxonomy on line 10 with your own custom taxonomy.

This example will only run once. If you prefer to let it run on every page load (which seems like an unnecessary waste of resources, unless you are testing/debugging), then delete lines 7, 8, 23, and 24.

 * Give all custom taxonomy terms a default value for a custom meta.
 * This will only run once.
function isa_update_custom_tax_terms_meta(){
	global $wpdb;
	// Run this update only once
	if (	get_option( 'isa_run_once_update_term_meta' ) != 'completed' ) {

		$terms = get_terms( 'your_custom_taxonomy' );

		foreach ($terms as $term) {

			$t_id = $term->term_id;
			$term_meta = array(
					'term_meta_key_1' => 999999,
					'term_meta_key_2' => 999999
			// Save the option array.
			update_option( "taxonomy_$t_id", $term_meta );

			update_option( 'isa_run_once_update_term_meta', 'completed' );
add_action ('init', 'isa_update_custom_tax_terms_meta' );

See more:


Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this: