tyxla / carbon-breadcrumbs

A basic WordPress plugin for breadcrumbs with advanced capabilities for extending.
GNU General Public License v2.0
18 stars 5 forks source link

Yoast SEO - primary category integration #41

Open pkostadinov-2create opened 6 years ago

pkostadinov-2create commented 6 years ago

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.

tyxla commented 6 years ago

@pkostadinov-2create nice 👍

Looks like this is a good example to have in the Usage & Examples section. Feel free to submit a PR for adding it to the README.

Thanks for this one 👍