Site logo

Archived topic

Dynamic data in Generateblocks : Display only primary category

7 replies · Started by Rudy on November 22, 2021

Viewing posts 1–8 of 8

Hi,

I'm building a blog layout using this video as a guide : https://www.youtube.com/watch?v=-ZTQP_KA2xE

When I set my dynamic content to display the category of the post, I'd like to be able to have only my primary category to be displayed.

It looks like it's not something I can do "easily" using generateblocks, but I'm sure someone have a bit of code to help me achieve the wanted output :)

Here is what it looks like now : https://www.screencast.com/t/MByR3ypfZ

Any help please ?

Thank you so much,

I read the other post but it's really technical for me. I pasted the last piece of code Tom provided in my functions.php file, but it's not working.

OK to break it down:

1. This gets added to your child theme functions.php - if you're not using a child theme then you should add it using the Code Snippets plugin:

function dynamic_category_link_function( $atts ) {
	if ( 'post' !== get_post_type() ) {
		return;
	}
    ob_start();

    $categories = get_the_category();
    $category_link = '';
	
    if ( class_exists('WPSEO_Primary_Term') ) {
        // Show the post's 'Primary' category, if this Yoast feature is available, & one is set
        $wpseo_primary_term = new WPSEO_Primary_Term( 'category', get_the_id() );
        $wpseo_primary_term = $wpseo_primary_term->get_primary_term();
        $term = get_term( $wpseo_primary_term );

        if ( is_wp_error( $term ) ) {
            // Default to first category (not Yoast) if an error is returned
            $category_link = get_category_link( $categories[0]->term_id );
            $term_name = get_term( $categories[0]->term_id  )->name;
        } else {
            // Yoast Primary category
            $category_link = get_category_link( $term->term_id );
            $term_name = get_term( $term->term_id )->name;
        }
    } else {
        // Default, display the first category in WP's list of assigned categories
        $category_link = get_category_link( $categories[0]->term_id );
        $term_name = get_term( $categories[0]->term_id  )->name;
    }

    echo '<a class="term-link" href="' . $category_link . '">' . $term_name .'</a>';
	
	return ob_get_clean();
	
}
add_shortcode( 'dynamic_category_link', 'dynamic_category_link_function' );

2. In your Block Element - add a GB Headline Block, and paste in the shortcode: [dynamic_category_link]

Let me know if that works

Thank you very much.

Now it pulls the right url for the primary navigation but it doesn't display the term, just the url, and it's not clickable.

you can see it here : https://www.screencast.com/t/DpJRLsFl

Thank you very much, it works perfectly :)

Awesome - glad to hear that!

This archived topic is closed to new replies.