0
votes

A have a lot of posts with custom post types in the database. In the same time the theme created the taxonomy institution:

function my_taxonomies_institutions() {
    $labels = array(
        'name'              => _x( 'Category', 'taxonomy general name' ),
        'singular_name'     => _x( 'Category', 'taxonomy singular name' ),
        // and tothers
    );
    $args = array(
        'labels'             => $labels,
        'hierarchical'       => true,
        'show_admin_column'  => true,
        'rewrite'            => array( 'hierarchical' => true, 'slug' => 'institutions' ),
    );
    register_taxonomy( 'institutions', 'institution', $args ); 
}
add_action( 'init', 'my_taxonomies_institutions', 0 );

OK, there's a menu item Instituitions in admin zone, and a bit of Categories there, for example - Sections. Now in order to animate the theme that constructed for this taxonomy I need to go through all posts and to attach the Instituitions term to the post depending of it's post_type.

print term_exists('sections'); // 7

I tried the following

$ret = wp_set_post_terms($pid, 7, 'institution');
$ret = wp_set_post_terms($pid, 'sections', 'institution');

but result was

WP_Error Object ( [errors] => Array ( [invalid_taxonomy] => Array ( [0] => Неверная таксономия. ) ) [error_data] => Array ( ) )

What I'm doing wrong?

2
in your code you are creating a ustom post not a taxnomy, take a look to this thread wordpress.stackexchange.com/questions/84921/…efirvida
Sorry, I posted another piece of code. Corrected.zzmaster

2 Answers

1
votes

You registered taxonomy with name institutions but using institution by mistake, hence te error [invalid_taxonomy]. It should be like this

$ret = wp_set_post_terms($pid, array(7,), 'institutions');
$ret = wp_set_post_terms($pid, array('sections',), 'institutions');

To assign this term "sections" with term_id = 7 to all posts of type institution, do something like

$posts = get_posts(array(
  'post_type' => 'institution',
  'post_status' => 'publish',
  'posts_per_page' => -1
));

foreach ( $posts as $post ) {
   wp_set_post_terms( $post->ID, array(7,), 'institutions');
   // OR 
   // wp_set_post_terms( $post->ID, array ('sections',), 'institutions');
}

I hope this will work. Please have a look at this codex page for further info.

0
votes

try something like:

$posts = get_posts([
  'post_type' => 'institution',
  'post_status' => 'publish',
  'numberposts' => -1
]);

foreach ( $posts as $post ) {
   wp_set_post_terms( $post->ID; array( ), 'institutions');
}

also if you want to wp_set_post_terms by id, you should use wp_set_post_terms( $post->ID; array( $id )) instead of wp_set_post_terms( $post->ID; $id) take a look here