1

Is there any way to insert a taxonomy term to different posts whose ids are known in bulk. For example, suppose we have custom post types with ids 4522, 4524, 4526, 4528 and 4530; how can I insert a taxonomy term 'football' in taxonomy 'sports'. Thanks The code used in index.php

    <?php
$post_ids = [57542, 57544, 57546, 57548, 57550, 57552, 57554, 57556, 57558, 57562, 57564, 57566, 57169, 57192, 57189]; // array of post ID's
foreach ( $post_ids as $id ) {
    if ( !has_term( 'geography', 'objective-questions', $id ) ) // Check if term is not yet attached to post 
        wp_set_post_terms(
            $id, // Post ID
            'geography', // Term slug ( or can be term ID )
            'objective-questions', // Taxonomy name
            true // Only append the term, do not replace
        );
}?>

1 Answer 1

2

I hope I understand this correctly. You can simply just add your post ID's in an array and then use a foreach loop to loop through the ID's and checking whether or not they have the term to assign or not, and if not, assign the term to the post

$post_ids = [4522, 4524, 4526, 4528, 4530]; // array of post ID's
foreach ( $post_ids as $id ) {
    if ( !has_term( 'footbal', 'sports', $id ) ) // Check if term is not yet attached to post 
        wp_set_object_terms (
            $id, // Post ID
            'footbal', // Term slug ( or can be term ID )
            'sports', // Taxonomy name
            true, // Only append the term, do not replace
        );
}
8
  • Thanks. But putting it in functions.php gives unexpected 'wp_set_post_terms' (T_STRING)
    – Skotlive
    Aug 13, 2015 at 13:11
  • Hello Pieter, I tried it but somehow it does not work.
    – Skotlive
    Aug 14, 2015 at 5:25
  • What exactly is happening or not happening? Aug 14, 2015 at 5:29
  • These are custom post types and already published. I suppose that by putting this code in functions.php should append the new term to every post with the given ids. I used your code and saved it in functions.php and it did nothing. Neither it threw an error nor my posts got the term.
    – Skotlive
    Aug 14, 2015 at 5:35
  • Just add the code in any template (like index.php), not functions.php, refresh the homepage, and it should be done. Remove the code afterwards Aug 14, 2015 at 5:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.