Skip to content

Instantly share code, notes, and snippets.

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 JoeyBurzynski/8e7fc3a2dc77b72be67d9eeadfa76252 to your computer and use it in GitHub Desktop.
Save JoeyBurzynski/8e7fc3a2dc77b72be67d9eeadfa76252 to your computer and use it in GitHub Desktop.
Wordpress (PHP): How to Programmatically Insert Taxonomy Terms [Slug Definition, Error Handling, and Logging]
<?php
// Programmatic Insertion of Taxonomy Terms with Slug Definition, Error Handling, and Logging
add_action('init', function () {
$taxonomyName = 'state';
// Check if the taxonomy exists
if (!taxonomy_exists($taxonomyName)) {
error_log("Taxonomy {$taxonomyName} does not exist.");
return;
}
$states = [
'AK' => 'Alaska', 'AL' => 'Alabama', 'AR' => 'Arkansas',
'AS' => 'American Samoa', 'AZ' => 'Arizona', 'CA' => 'California',
'CO' => 'Colorado', 'CT' => 'Connecticut', 'DC' => 'District of Columbia',
'DE' => 'Delaware', 'FL' => 'Florida', 'GA' => 'Georgia',
'GU' => 'Guam', 'HI' => 'Hawaii', 'IA' => 'Iowa',
'ID' => 'Idaho', 'IL' => 'Illinois', 'IN' => 'Indiana',
'KS' => 'Kansas', 'KY' => 'Kentucky', 'LA' => 'Louisiana',
'MA' => 'Massachusetts', 'MD' => 'Maryland', 'ME' => 'Maine',
'MI' => 'Michigan', 'MN' => 'Minnesota', 'MO' => 'Missouri',
'MS' => 'Mississippi', 'MT' => 'Montana', 'NC' => 'North Carolina',
'ND' => 'North Dakota', 'NE' => 'Nebraska', 'NH' => 'New Hampshire',
'NJ' => 'New Jersey', 'NM' => 'New Mexico', 'NV' => 'Nevada',
'NY' => 'New York', 'OH' => 'Ohio', 'OK' => 'Oklahoma',
'OR' => 'Oregon', 'PA' => 'Pennsylvania', 'PR' => 'Puerto Rico',
'RI' => 'Rhode Island', 'SC' => 'South Carolina', 'SD' => 'South Dakota',
'TN' => 'Tennessee', 'TX' => 'Texas', 'UT' => 'Utah',
'VA' => 'Virginia', 'VI' => 'Virgin Islands', 'VT' => 'Vermont',
'WA' => 'Washington', 'WI' => 'Wisconsin', 'WV' => 'West Virginia',
'WY' => 'Wyoming',
];
foreach ($states as $slug => $name) {
if (empty(term_exists($slug, $taxonomyName))) {
$inserted_term = wp_insert_term($name, $taxonomyName, ['slug' => $slug]);
if (is_wp_error($inserted_term)) {
error_log("Error inserting term {$name}: " . $inserted_term->get_error_message());
} else {
// Optional: Uncomment to log successful insertions
// error_log("Inserted term {$name} successfully.");
}
}
}
}, 999);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment