Skip to content

Instantly share code, notes, and snippets.

@neovea
Last active August 29, 2015 14:08
Show Gist options
  • Save neovea/157ba941203c8dcccb29 to your computer and use it in GitHub Desktop.
Save neovea/157ba941203c8dcccb29 to your computer and use it in GitHub Desktop.
Get a specific category obj depending on the field (name, slug or id) and the value of the field.
<?php
/**
* Return a product obj depending on field and value
* Authorised fields : term_id, name, slug
* @author Franck LEBAS
* @param string $field
* @param string $value
* @return obj, array or string $response
*/
function wc_get_product_category($field, $value) {
$authorized_fields = array(
'term_id',
'name',
'slug'
);
// Check if field and value are set and not empty
if (!isset($field) || empty($field) || !isset($value) || empty($value)) {
$response = "Error : check your args, some are not set or are empty.";
}
else {
// Check if the specified field is part of the authorised ones
if (!in_array($field, $authorized_fields)) {
$response = "Unauthorised field $field"; }
else {
// init exists var to determine later if specified value matches
$exists = false;
$product_cats = get_terms('product_cat', array(
'hide_empty' => 0,
'orderby' => 'name'
));
// the loop will stop once it will have found the matching value in categories
foreach ($product_cats as $product_cat) {
if($product_cat->$field == $value) {
$response = $product_cat;
$exists = true;
break;
}
}
if ($exists == false) {
$response = array(
"message" => "Error with specified args",
"field" => "$field",
"value" => "$value"
);
}
}
}
return $response;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment