Skip to content

Instantly share code, notes, and snippets.

@cyberdev
Last active April 28, 2024 06:04
Show Gist options
  • Save cyberdev/fae017d1a31301508c57ae1c41c30b85 to your computer and use it in GitHub Desktop.
Save cyberdev/fae017d1a31301508c57ae1c41c30b85 to your computer and use it in GitHub Desktop.
Set Category For Product
<?php
private function set_product_category_item($category, $parent_id = null)
{
$taxonomy = 'product_cat';
if (term_exists($category, $taxonomy)) {
$category_id = get_term_by('name', $category, $taxonomy)->term_id;
} else {
//$term_data = wp_insert_term($attributes['parent2'], $taxonomy, ['parent' => $parent_id_1]);
if(!empty($parent_id)) {
$term_data = wp_insert_term($category, $taxonomy, ['parent' => $parent_id]);
} else {
$term_data = wp_insert_term($category, $taxonomy);
}
if(is_wp_error($term_data)) {
$category_id = null;
} else {
$category_id = $term_data['term_id'];
}
}
return $category_id;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment