Primary Term for Posts using The SEO Framework in Bricks

Updated on 18 Mar 2024

The SEO Framework is one of the better (coding-wise) SEO plugins.

Like Yoast and Rank Math, it has the option to specify a category or a term as primary when editing posts.

This Pro tutorial provides the steps to output the linked primary term and all other linked terms of the current post (either in single view or in a query loop) separately in Bricks.

Step 1

Let’s define a custom function that takes the taxonomy as the first argument and the primary term object’s property to retrieve (defaults to name) as the second argument.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

function bl_get_primary_tax( string $tax, string $prop = 'name' ): string {
    // $term_id = get_post_meta( get_the_ID(), "_primary_term_$tax", true );
    // $term = get_term_by( 'id', $term_id, $tax );

    $term = function_exists( 'tsf' ) ? tsf()->get_primary_term( get_the_ID(), $tax ) : 0;
    $term = $term ?: ( get_the_terms( get_the_ID(), $tax )->term ?? 0 );

    if ( $prop === 'url' || $prop === 'link' ) {
        return esc_url( get_term_link( $term, $tax ) );
    }

    return is_object( $term ) ? $term->$prop : '';
}

Whitelist the function.

Usage in Bricks editor:

For outputting the name of the primary genre term:

{echo:bl_get_primary_tax(genre)}

For the term link:

{echo:bl_get_primary_tax(genre, url)}

If you are curious as to what other properties are available:

Step 2

Here’s how you can output all the other terms i.e, exclude the primary term.

Add a Container (HTML tag of ul) and inside it, a Block (HTML tag of li).

Custom CSS for the Block:

%root% {
	list-style: none;
}

Enable query loop on the Block.

Type: Terms

Select your taxonomy.

Enable “Current post term”.

Add a Text Link inside the Block and set it like this:

If you check the front end of any post that has some terms set, it will now show all the terms including the primary one.

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php 

// Filter the terms to exclude the post's primary term when using The SEO Framework
add_filter( 'bricks/terms/query_vars', function( $query_vars, $settings, $element_id ) {
    if ( $element_id !== 'ohhnpp' ) return $query_vars;

    $term_id = get_post_meta( get_the_ID(), "_primary_term_genre", true );
    
    $query_vars['exclude'] = [$term_id];

    return $query_vars;
}, 10, 3 );

Replace ohhnpp with the Bricks ID of your query loop element.

Replace genre with the name of your taxonomy.

References

https://kb.theseoframework.com/kb/data-stored-in-your-database/#tsf-post

https://wordpress.org/support/topic/primary-category-and-link-to-category-page/#post-15381200