I would like to insert (not replace) categories that already exists in my website wordpress. I tried this way:
global $wpdb;
$products = $wpdb->get_results("SELECT ID FROM `" . $wpdb->prefix . "posts` where post_type='product'");
foreach ($products as $product) {
$array = [];
array_push($array, 1021);
array_push($array, 1042);
array_push($array, 1040);
wp_set_post_categories(38691, $array, true);
}
But unfortunately my code is not working. The numbers 1021, 1042, 1040 is the category ID and 38691 is the product ID. Someone can help me?
CodePudding user response:
You could use wp_set_post_terms()
to insert categories.
global $wpdb;
$products = $wpdb->get_results("SELECT ID FROM `" . $wpdb->prefix . "posts` where post_type='product'");
foreach ($products as $product) {
$product_id = $product->ID;
$categories = array(1021, 1042, 1040);
wp_set_post_terms($product_id, $categories, 'product_cat', true);
}
The true
tells WordPress to append new categories instead of replacing them