[ad_1]
I have a custom theme in my WordPress website and I have custom taxonomies inside it. Every time a create a new post, I create new terms within the taxonomies and I want to retrieve the IDs and names of these newly created terms. Can I do that? Will I need to use REST API or some plugin? Please help, thank you.
[ad_2]
It’s definitely possible to retrieve the IDs and names of newly created terms within custom taxonomies in WordPress without necessarily resorting to the REST API or plugins.
Since you’re working with a custom theme and taxonomies, you can utilize WordPress hooks and functions to achieve this functionality. Specifically, you can hook into the `save_post` action, which fires after a post has been saved or updated. Within this hook, you can check for the taxonomy terms associated with the post and retrieve their IDs and names.
Here’s a basic example of how you can achieve this:
phpCopy code
// Hook into save_post action
add_action(‘save_post’, ‘retrieve_new_taxonomy_terms’);
function retrieve_new_taxonomy_terms($post_id) {
// Check if it’s not an autosave and if it’s a post type you’re interested in
if ( ! wp_is_post_autosave( $post_id ) && ! wp_is_post_revision( $post_id ) && ‘your_custom_post_type’ === get_post_type($post_id) ) {
// Get the terms for your custom taxonomy
$terms = wp_get_post_terms($post_id, ‘your_custom_taxonomy’, array(‘fields’ => ‘all’));
// Loop through the terms and retrieve their IDs and names
foreach ($terms as $term) {
$term_id = $term->term_id;
$term_name = $term->name;
// Do something with the term IDs and names (e.g., echo or store them)
echo “Term ID: {$term_id}, Term Name: {$term_name}<br>”;
}
}
}
Replace `’your_custom_post_type’` with the slug of your custom post type and `’your_custom_taxonomy’` with the slug of your custom taxonomy.
You can place this code in your theme’s `functions.php` file or in a custom plugin. After adding this code, whenever you create or update a post, the newly created terms within your custom taxonomy will be retrieved and their IDs and names will be displayed or processed according to your needs.
Hope this helps! Let me know if you have any questions or need further assistance.