Skip to content

Commit

Permalink
add util to fetch primary category
Browse files Browse the repository at this point in the history
  • Loading branch information
Sidsector9 committed Oct 30, 2022
1 parent 01e0adb commit a89b50b
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
2 changes: 1 addition & 1 deletion includes/functions/content-sync.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
25 changes: 25 additions & 0 deletions includes/functions/utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit a89b50b

Please sign in to comment.