Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AIFW - Will create categories if not found.
<?php
/**
* Plugin Name: AIFW Create Categories
* Description: Will create categories if not found.
* Version: 1.0.0
* Author: Mário Valney
* Author URI: https://mariovalney.com
* Text Domain: aifw-create-categories
*
* @link https://github.com/mariovalney/api-improver-for-woocommerce
*/
add_filter( 'aifw_api_v3_products_term_not_found', 'aifwcc_create_category_if_term_not_found', 10, 1 );
/**
* Add a category when AIFW is not able to find a term by name/slug.
*
* Return a empty value to ignore or a valid ID to be added to Product.
* You can use it to create a term and return it ID, for example.
*
* @param integer $term_id The category/tag ID.
* @param array $params The category/tag object.
* @param string $taxonomy The taxonomy (product_cat|product_tag).
*/
function aifwcc_create_category_if_term_not_found( $term_id, $params, $taxonomy ) {
if ( $taxonomy !== 'product_cat' ) {
return $term_id;
}
$name = $params['name'] ?? $params['slug'];
$options = [];
if ( ! empty( $params['slug'] ) ) {
$options['slug'] = $params['slug'];
}
$term = wp_insert_term( $name, 'product_cat', $options );
if ( is_wp_error( $term ) || empty( $term['term_id'] ) ) {
return $term_id;
}
return $term['term_id'];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment