Created
August 14, 2020 03:21
-
-
Save trvswgnr/01965dfbd6a836fac8aa084e683d10f7 to your computer and use it in GitHub Desktop.
WooCommerce get primary category for product
This file contains hidden or 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 | |
/** | |
* Get a product's primary category using Yoast when available. | |
*/ | |
function get_product_primary_category() { | |
global $product; | |
// if Yoast is being used, utilize it to get the primary category. | |
if ( function_exists( 'yoast_get_primary_term_id' ) ) { | |
$primary_category_id = yoast_get_primary_term_id( 'product_cat' ); | |
$category = get_term( $primary_category_id ); | |
} | |
if ( ! function_exists( 'yoast_get_primary_term_id' ) || is_wp_error( $category ) ) { | |
$categories = get_the_terms( $product->get_id(), 'product_cat' ); | |
$category = ! empty( $categories ) ? $categories[0] : false; | |
} | |
if ( ! empty( $category ) && ! is_wp_error( $category ) ) { | |
return (object) array( | |
'name' => $category->name, | |
'slug' => $category->slug, | |
'permalink' => get_term_link( $category->slug, 'product_cat' ), | |
); | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment