WordPress / 7 MIN READ
Woo Create Categories PHP
Creating WooCommerce categories with PHP
From the original Fervor library. Examples may use older package versions.
Tutorial: Creating and Implementing Categories with PHP for WooCommerce
In this tutorial, you’ll learn how to create product categories programmatically in WooCommerce using PHP and how to assign products to these categories dynamically. This is especially useful if you’re setting up a store or migrating data without using the WordPress admin panel.
Overview
We’ll cover:
- Creating Categories Programmatically.
- Assigning Products to Categories.
- Displaying Categories in Your Store.
Step 1: Create Categories Programmatically
WooCommerce categories are stored as WordPress taxonomy terms under the taxonomy product_cat. We can create these categories using WordPress’s wp_insert_term() function.
Code Example: Creating Categories
Add the following code to your theme’s functions.php file or a custom plugin:
function create_woocommerce_categories() {
// Check if the category already exists
if (!term_exists('Shoes', 'product_cat')) {
// Create a new category
wp_insert_term(
'Shoes', // Name of the category
'product_cat', // Taxonomy slug
array(
'description' => 'Stylish and comfortable shoes for all occasions.',
'slug' => 'shoes',
'parent' => 0, // 0 means no parent (top-level category)
)
);
}
if (!term_exists('Running Shoes', 'product_cat')) {
// Create a subcategory under "Shoes"
$parent_term = get_term_by('slug', 'shoes', 'product_cat');
wp_insert_term(
'Running Shoes',
'product_cat',
array(
'description' => 'High-performance running shoes.',
'slug' => 'running-shoes',
'parent' => $parent_term->term_id,
)
);
}
}
add_action('init', 'create_woocommerce_categories');
How It Works
term_exists()checks if the category already exists.wp_insert_term()creates the category if it doesn’t exist.- The
parentargument allows you to define hierarchical relationships (subcategories).
Step 2: Assign Products to Categories
You can assign categories to products programmatically using the wp_set_object_terms() function.
Code Example: Assigning Products to Categories
function assign_product_to_category($product_id, $category_slug) {
// Assign the product to a category
wp_set_object_terms($product_id, $category_slug, 'product_cat');
}
// Example usage: Assign product ID 123 to the "Running Shoes" category
assign_product_to_category(123, 'running-shoes');
How It Works
$product_idis the ID of the product you want to assign to the category.$category_slugis the slug of the category.
To get the product ID, you can:
- Check in WooCommerce > Products > Hover over a product to see its ID.
- Programmatically retrieve it (e.g., from a query).
Step 3: Display Categories in Your Store
WooCommerce provides several ways to display categories on your store, including shortcodes, templates, and custom PHP functions.
Method 1: Display Categories Using a Shortcode
Add this shortcode to a page or post:
[product_categories number="12" parent="0"]
number="12": Limits the number of categories displayed.parent="0": Displays only top-level categories.
Method 2: Display Categories with PHP
Use WooCommerce’s built-in functions to display categories in your theme:
function display_product_categories() {
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true, // Show only categories with products
);
$categories = get_terms($args);
if (!empty($categories)) {
echo '<ul class="product-categories">';
foreach ($categories as $category) {
echo '<li>';
echo '<a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a>';
echo '</li>';
}
echo '</ul>';
}
}
add_action('woocommerce_before_shop_loop', 'display_product_categories');
How It Works
get_terms()retrieves the categories based on your criteria.get_term_link()generates the URL for each category.- The
add_action()hook integrates the function into WooCommerce’s shop page.
Step 4: Combine It All
If you want to create categories, assign products, and display them on your store, combine the above steps into one streamlined workflow. For example:
function setup_categories_and_assign_products() {
// Step 1: Create Categories
if (!term_exists('Accessories', 'product_cat')) {
wp_insert_term(
'Accessories',
'product_cat',
array(
'description' => 'Fashionable accessories for everyone.',
'slug' => 'accessories',
'parent' => 0,
)
);
}
// Step 2: Assign a product to "Accessories"
$product_id = 456; // Replace with your actual product ID
wp_set_object_terms($product_id, 'accessories', 'product_cat');
}
add_action('init', 'setup_categories_and_assign_products');
Testing Your Code
- Save your changes to the
functions.phpfile or plugin. - Refresh your site.
- Check:
- WooCommerce Categories Page: See if the categories were created.
- Product Page: Verify the product is assigned to the correct category.
Advanced Tips
-
Batch Assign Products: Use loops to assign multiple products at once:
$products = array(123, 124, 125); // Replace with product IDs foreach ($products as $product_id) { assign_product_to_category($product_id, 'shoes'); } -
Customize Category Attributes: Add custom fields to categories using hooks and metadata.
-
Use a Plugin for Complex Tasks: For non-developers, plugins like WP All Import can simplify category creation and product assignments.
Conclusion
By following this tutorial, you’ve learned how to programmatically create and manage WooCommerce categories using PHP. This approach is perfect for bulk setups or automation.
Bonus
Tutorial: Creating Categories with Parent Categories in WooCommerce Using PHP
In this tutorial, we’ll build on the basics of creating categories programmatically in WooCommerce by adding parent categories. This is ideal for creating a hierarchical category structure, such as:
- Parent Category: Shoes
- Child Categories: Running Shoes, Formal Shoes, Sneakers
Overview
- Create parent categories.
- Create child categories and assign them to parents.
- Verify the hierarchy.
- (Optional) Assign products to child categories.
Step 1: Create Parent Categories
Parent categories are top-level categories with no parent. Use the wp_insert_term() function to create them.
Code Example: Creating Parent Categories
Add this to your functions.php file or a custom plugin:
function create_parent_categories() {
// Check if the parent category exists
if (!term_exists('Shoes', 'product_cat')) {
wp_insert_term(
'Shoes', // Category Name
'product_cat', // Taxonomy
array(
'description' => 'A wide selection of shoes for all occasions.',
'slug' => 'shoes', // Custom URL slug
'parent' => 0, // 0 indicates no parent (top-level category)
)
);
}
if (!term_exists('Bags', 'product_cat')) {
wp_insert_term(
'Bags',
'product_cat',
array(
'description' => 'Stylish and functional bags for everyday use.',
'slug' => 'bags',
'parent' => 0,
)
);
}
}
add_action('init', 'create_parent_categories');
What’s Happening Here
term_exists()checks if a category already exists.parent => 0means this category is a top-level category.
Step 2: Create Child Categories and Assign Them to Parents
Child categories are created just like parent categories, but with a parent ID specified.
Code Example: Creating Child Categories
function create_child_categories() {
// Get the parent category ID
$parent_term = get_term_by('slug', 'shoes', 'product_cat');
if ($parent_term && !term_exists('Running Shoes', 'product_cat')) {
wp_insert_term(
'Running Shoes', // Category Name
'product_cat', // Taxonomy
array(
'description' => 'High-performance running shoes.',
'slug' => 'running-shoes', // Custom URL slug
'parent' => $parent_term->term_id, // Assign parent ID
)
);
}
if ($parent_term && !term_exists('Sneakers', 'product_cat')) {
wp_insert_term(
'Sneakers',
'product_cat',
array(
'description' => 'Trendy sneakers for casual wear.',
'slug' => 'sneakers',
'parent' => $parent_term->term_id, // Assign parent ID
)
);
}
}
add_action('init', 'create_child_categories');
What’s Happening Here
get_term_by()retrieves the parent category by its slug (shoes).- The
parentargument specifies the ID of the parent category. - Subcategories (
Running ShoesandSneakers) are created and assigned to the parent (Shoes).
Step 3: Verify the Hierarchy
- Go to Products > Categories in your WordPress dashboard.
- You should see the following structure:
- Shoes
- Running Shoes
- Sneakers
- Bags
- Shoes
Step 4: Assign Products to Child Categories
Now that the hierarchy is ready, you can assign products to the child categories programmatically.
Code Example: Assign Products to Child Categories
function assign_products_to_child_categories() {
// Assign product ID 123 to "Running Shoes"
wp_set_object_terms(123, 'running-shoes', 'product_cat');
// Assign product ID 124 to "Sneakers"
wp_set_object_terms(124, 'sneakers', 'product_cat');
}
add_action('init', 'assign_products_to_child_categories');
What’s Happening Here
wp_set_object_terms()assigns the product ID (123,124) to the specified category slug (running-shoes,sneakers).- Ensure the product IDs are valid and exist in your store.
Optional: Display the Category Hierarchy
You can display the category hierarchy dynamically on the front end using WooCommerce functions.
Code Example: Display Category Hierarchy
function display_category_hierarchy() {
$args = array(
'taxonomy' => 'product_cat',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
);
$categories = get_terms($args);
if (!empty($categories)) {
echo '<ul class="product-categories">';
foreach ($categories as $category) {
if ($category->parent == 0) {
// Display top-level categories
echo '<li>' . esc_html($category->name);
// Display child categories
$child_args = array(
'taxonomy' => 'product_cat',
'parent' => $category->term_id,
'hide_empty' => false,
);
$child_categories = get_terms($child_args);
if (!empty($child_categories)) {
echo '<ul>';
foreach ($child_categories as $child) {
echo '<li>' . esc_html($child->name) . '</li>';
}
echo '</ul>';
}
echo '</li>';
}
}
echo '</ul>';
}
}
add_action('woocommerce_before_shop_loop', 'display_category_hierarchy');
What’s Happening Here
- The first
get_terms()fetches all categories. - Child categories are filtered by checking
parent == $category->term_id. - The structure is displayed as nested
<ul>elements.
Testing the Code
- Activate the Code: Save the changes to
functions.phpor your plugin file. - Check WooCommerce Categories:
- Verify the parent-child hierarchy under Products > Categories.
- Assign Products:
- Ensure the products appear in the assigned categories.
- View the Shop:
- Check the category hierarchy on the shop page (if you’ve added the display code).
Conclusion
Congratulations! You’ve now created a hierarchical category structure in WooCommerce programmatically. With these skills, you can automate category creation, manage large catalogs, and dynamically display categories in your store.