When managing content in WordPress, one may often need to programmatically create terms within a taxonomy. Whether you are setting up a site for the first time or automating content management tasks, understanding how to efficiently generate terms can streamline your processes. Here, we will discuss how to use a PHP array to create terms in a specified category using WordPress functions.
Prerequisites
Ensure you have administrative access to your WordPress site, enabling you to edit the functions.php file of your active theme
Step 1: Define Your Terms
Start by creating a PHP array that holds the names of the terms you want to add. These terms could be anything relevant to your content strategy:
1 2 | // Array of term names $terms = ['Term 1', 'Term 2', 'Term 3', 'Term 4', 'Term 5', 'Term 6', 'Term 7', 'Term 8', 'Term 9', 'Term 10']; |
Step 2: Specify the Taxonomy
Identify the taxonomy in which these terms should be inserted. This could be a default taxonomy like 'category' or a custom taxonomy you have previously defined:
1 2 | // The taxonomy ID or name to which terms will be added $taxonomy = 'category'; // Replace this with your specific taxonomy |
Step 3: Insert Terms Using a Loop
To insert each term into the specified taxonomy, use a loop to iterate through the term names and the wp_insert_term function to add each one:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function create_my_custom_terms() { $terms = ['Term 1', 'Term 2', 'Term 3', 'Term 4', 'Term 5', 'Term 6', 'Term 7', 'Term 8', 'Term 9', 'Term 10']; $taxonomy = 'category'; // Replace this with your specific taxonomy foreach ($terms as $term_name) { $result = wp_insert_term( $term_name, // The name of the term $taxonomy // The taxonomy ); if (is_wp_error($result)) { echo 'Error adding term: ' . $result->get_error_message(); } else { echo 'Term "' . $term_name . '" successfully added with ID ' . $result['term_id'] . '<br>'; } } } |
Step 4: Hook into WordPress Initialization
To ensure that your function runs only after WordPress has loaded all necessary components, hook your function into the init action:
1 2 | // Adding our function to the 'init' hook add_action('init', 'create_my_custom_terms'); |
Deployment
Add this code to the functions.php file in your WordPress theme directory. The code will execute when the site loads, ensuring all terms are added to the database. Be mindful that if this script runs repeatedly, it may attempt to recreate existing terms, which is inefficient for a production environment. After verifying that the terms have been added, you might want to disable or remove the script.
