From b9d774317aba6c3cdf2857150962ea0ed3632ab3 Mon Sep 17 00:00:00 2001 From: Siddharth Thevaril Date: Sun, 30 Oct 2022 20:36:10 +0530 Subject: [PATCH] add util to fetch primary category --- includes/functions/content-sync.php | 2 +- includes/functions/utils.php | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/includes/functions/content-sync.php b/includes/functions/content-sync.php index 9920d103..999ab1af 100644 --- a/includes/functions/content-sync.php +++ b/includes/functions/content-sync.php @@ -276,7 +276,7 @@ function get_post_data( $post ) { 'plainText' => wp_strip_all_tags( $content ), 'size' => str_word_count( wp_strip_all_tags( $content ) ), 'allSections' => Utils\get_post_categories_paths( $post->ID ), - 'sectionNames' => Utils\get_post_categories( $post->ID ), + 'sectionNames' => Utils\get_primary_category( $post->ID ), 'modifiedAt' => gmdate( \DateTime::RFC3339, strtotime( $post->post_modified_gmt ) ), 'tags' => Utils\get_post_tags( $post ), 'url' => $permalink, diff --git a/includes/functions/utils.php b/includes/functions/utils.php index 375954ee..9ce7edb4 100644 --- a/includes/functions/utils.php +++ b/includes/functions/utils.php @@ -545,3 +545,28 @@ function get_post_categories( $post_id ) { function get_wp_sophi_versions() { return 'wp-' . get_bloginfo( 'version' ) . ':plugin-' . SOPHI_WP_VERSION; } + +/** + * Get the primary term name. + * + * @param string $taxonomy Optional. The taxonomy to get the primary term ID for. Defaults to category. + * @param int $post_id Optional. Post to get the primary term ID for. + * + * @return string + */ +function get_primary_category( $post_id = 0, $taxonomy = 'category' ) { + if ( ! function_exists( 'yoast_get_primary_term_id' ) ) { + $post_terms = wp_get_post_terms( $post_id, $taxonomy ); + + if ( is_array( $post_terms ) && count( $post_terms ) > 0 ) { + return $post_terms[0]->name; + } else { + return ''; + } + } + + $primary_term_id = yoast_get_primary_term_id( $taxonomy, $post_id ); + $primary_category = get_term( $primary_term_id ); + + return $primary_category->name; +}