carbon-breadcrumbs icon indicating copy to clipboard operation
carbon-breadcrumbs copied to clipboard

Yoast SEO - primary category integration

Open pkostadinov-2create opened this issue 6 years ago • 1 comments

A fun and useful thing to have would be Yoast SEO integration for their feature "Primary Category".

Here is some reference code that I use to integrate the Yoast SEO Primary Category feature:

add_action( 'carbon_breadcrumbs_after_setup_trail', array( $this, 'modify_breadcrumbs' ) );
function modify_breadcrumbs( $trail ) {
	global $post;
	if ( ! is_singular( 'post' ) ) {
		return;
	}

	$cats = get_the_category( $post->ID );
	if ( empty( $cats ) || empty( $cats[0] ) ) {
		return;
	}
	$cats = wp_list_sort( $cats, array(
		'term_id' => 'ASC',
	) );

	/**
	 * Call the filter,
	 * triggering YoastSEO primary category modification
	 */
	$category_object = apply_filters( 'post_link_category', $cats[0], $cats, $post );

	$term_id = $category_object->term_id;

	/**
	 * Taxonomy breadcrumb is inserted at 700
	 * Removing it, and adding new one at the same priority
	 */
	$trail->remove_item_by_priority( 700 );

	$terms = Carbon_Breadcrumb_Locator::factory( 'term', 'category' );
	$items = $terms->get_items( 700, $term_id );

	if ( $items ) {
		$trail->add_item( $items );
	}
}

Using post_link_category can potentially lead to longer support, compared to YoastSEO internal methods.

Let me know if you are interested in this feature, and I will provide a fork.

pkostadinov-2create avatar Mar 06 '18 15:03 pkostadinov-2create