I have imported tens of thousands of products into Woocommerce but they are not assigned to any category. How can I assign a category (for example the default category) to all the products in my catalog? Thanks
The option to do it with the back office would be much too long of course, I'm looking for the SQL query instead, or a plugin maybe?
Something like that should do the trick. Backup before doing it !
UPDATE wp_term_relationships AS tr
JOIN wp_term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
JOIN wp_terms AS t ON tt.term_id = t.term_id
JOIN wp_posts AS p ON tr.object_id = p.ID
SET tt.term_taxonomy_id = {your_category_id}
WHERE tt.taxonomy = 'product_cat'
AND p.post_type = 'product';
Replace wp_ with your prefix if its different. Replace {your_category_id} with the ID of the category you aim.
Another way is using a function
function assign_all_products_to_category() {
$category_id = 123; // Replace with the actual ID of your target product category
// Get all product IDs
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
);
$products = get_posts( $args );
if ( $products ) {
foreach ( $products as $product ) {
$product_id = $product->ID;
wp_set_object_terms( $product_id, $category_id, 'product_cat', true );
}
echo 'All products have been assigned to the category successfully.';
} else {
echo 'No products found.';
}
}
Execute the function as you see fit.
For example run it as url
function check_custom_param() {
if ( isset( $_GET['run_function'] ) && $_GET['run_function'] === 'assign_products' ) {
assign_all_products_to_category();
exit; // Terminate script execution after running the function
}
}
add_action( 'template_redirect', 'check_custom_param' );
Your url should look like: http://example.com/?run_function=assign_products
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments