Archived topic
Displaying primary category on homepage using shortcode via content template
2 replies · Started by Yulia on September 3, 2022
Hi, there are similar posts on this topic, but I'm using The SEO Framework (TSF) to manage my primary category.
I'm trying to show a primary category as a clickable link using a shortcode on homepage using content template block.
Below is the shortcode that was provided by @cybr from TSF and it works as intended on regular post pages in GeneratePress.
No information is displayed when used on homepage, not even [shortcode_name].
add_shortcode( 'dynamic_term_link', 'dynamic_term_link_function' );
/**
* Dynamically fetches the primary term from TSF.
* If none is set, or TSF is inactive, it returns the first term found.
*
* @return string The primary term link for the current post.
*/
function dynamic_term_link_function() {
if ( ! is_single() ) return;
$post_type = get_post_type();
$id = get_the_ID();
$taxonomy = current( get_object_taxonomies( $post_type, 'objects' ) )->name ?? false;
if ( ! $taxonomy ) return '';
$primary_term_id = function_exists( 'tsf' ) ? tsf()->get_primary_term( $id, $taxonomy ) : 0;
$primary_term_id = $primary_term_id ?: ( get_the_terms( get_the_ID(), $taxonomy )[0]->term_id ?? null );
if ( $primary_term_id ) {
$term = get_term( $primary_term_id, $taxonomy );
$term_link = get_term_link( $term );
$term_name = $term->name ?? '';
if ( $term_link && $term_name )
return sprintf(
'<a class="gb-headline-text" href="%s">%s</a>',
esc_url( $term_link ),
esc_html( $term_name )
);
}
return '';
}
How to make it work on homepage?
Figured it out.
Just need to remove this line if ( ! is_single() ) return;.
Here is the updated shortcode that works anywhere on the website:
add_shortcode( 'dynamic_category_link', 'dynamic_term_link_function' );
/**
* Dynamically fetches the primary term from TSF.
* If none is set, or TSF is inactive, it returns the first term found.
*
* @return string The primary term link for the current post.
*/
function dynamic_term_link_function() {
$post_type = get_post_type();
$id = get_the_ID();
$taxonomy = current( get_object_taxonomies( $post_type, 'objects' ) )->name ?? false;
if ( ! $taxonomy ) return '';
$primary_term_id = function_exists( 'tsf' ) ? tsf()->get_primary_term( $id, $taxonomy ) : 0;
$primary_term_id = $primary_term_id ?: ( get_the_terms( get_the_ID(), $taxonomy )[0]->term_id ?? null );
if ( $primary_term_id ) {
$term = get_term( $primary_term_id, $taxonomy );
$term_link = get_term_link( $term );
$term_name = $term->name ?? '';
if ( $term_link && $term_name )
return sprintf(
'<a class="gb-headline-text" href="%s">%s</a>',
esc_url( $term_link ),
esc_html( $term_name )
);
}
return '';
}
Cheers!
Glad to hear and thanks for sharing your solutions!