Last active
May 21, 2020 16:03
-
-
Save gerrgg/29fa44063cb60ad76c26efd2e64d928a to your computer and use it in GitHub Desktop.
Gets a product's category, sort terms by category hierarchy and add term description to product content.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function msp_maybe_category_description( $content ){ | |
/** | |
* Gets current product category, sorts terms in hierarchy order | |
* | |
* @param string $content | |
* @return string $content | |
*/ | |
if( is_product() ){ | |
global $product; | |
$terms = get_terms( array( | |
'object_ids' => $product->get_id(), | |
'taxonomy' => 'product_cat', | |
)); | |
// sort into Hierarchys | |
$sorted_terms = msp_sort_terms_to_hierarchy( $terms ); | |
foreach( $sorted_terms as $terms ){ | |
// do children | |
if( isset( $terms->children ) ){ | |
foreach( $terms->children as $term ){ | |
$content .= msp_get_term_description( $term ); | |
} | |
} | |
// do parent; | |
$content .= msp_get_term_description( $terms ); | |
} | |
} | |
// must always return content (leave outside if ^^) | |
return $content; | |
} | |
function msp_get_term_description( $term ){ | |
/** | |
* Extracts term description if there is one and returns html | |
* @param WP_Term $term | |
* @return string $html | |
*/ | |
$html = ''; | |
if( ! is_wp_error( $term ) && ! empty( $term->description ) ){ | |
$html .= sprintf( "<h5>%s</h5>%s", $term->name, $term->description ); | |
} | |
return $html; | |
} | |
function msp_sort_terms_to_hierarchy($terms){ | |
/** | |
* Sorts taxonomies into set hierarchy | |
* @param array $terms | |
* @return array $terms | |
*/ | |
if( empty( $terms ) ) return false; | |
foreach($terms as $key => $term){ | |
if($term->parent != 0){ | |
$terms[$term->parent]->children[] = $term; | |
unset($terms[$key]); | |
} | |
} | |
return array_reverse( $terms ); | |
} | |
/** | |
* Allow HTML in term (category, tag) descriptions | |
*/ | |
foreach ( array( 'pre_term_description' ) as $filter ) { | |
remove_filter( $filter, 'wp_filter_kses' ); | |
if ( ! current_user_can( 'unfiltered_html' ) ) { | |
add_filter( $filter, 'wp_filter_post_kses' ); | |
} | |
} | |
foreach ( array( 'term_description' ) as $filter ) { | |
remove_filter( $filter, 'wp_kses_data' ); | |
} | |
/** | |
* =================================================== | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment