Wordpress - How can I get only parent terms?
Yes, just pass in the parent parameter to get_terms
when you call it, as Michael pointed out.
Since WP 4.5 this is the recommend usage:
$myterms = get_terms( array( 'taxonomy' => 'taxonomy_name', 'parent' => 0 ) );
Prior to WP 4.5 this was the default usage:
$myterms = get_terms( 'taxonomy_name_here', array( 'parent' => 0 ) );
Will return all terms that have a parent value of 0
, ie. top level terms.
use the 'parent' parameter:
http://codex.wordpress.org/Function_Reference/get_terms
or
http://codex.wordpress.org/Function_Reference/get_categories
for woocommerce email templates use the following:
$terms = get_the_terms( $_product->id , 'product_cat');
if($terms) {
foreach( $terms as $term ) {
$term = get_term_by("id", $term->parent, "product_cat");
if ($term->parent > 0) {
$term = get_term_by("id", $term->parent, "product_cat");
}
$cat_obj = get_term($term->term_id, 'product_cat');
$cat_name = $cat_obj->name;
}
}
echo '<br />('. $cat_name . ')';