Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I insert categories in products in wordpress by code?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading