Archived topic
Custom archive page with customized list of terms on each post
5 replies · Started by Utopia - Arquitectura e Engenharia Lda on January 31, 2023
Hi,
I am customizing archive pages and I am stuck with a button displaying categories for each post.
I know how to create a button that displays the categories of each post.
Then I select the block and choose:
DYNAMIC TEXT TYPE - List of terms
TAXONOMY - category
DYNAMIC LINK TYPE - Term archives
The problem is that I have archives for parent categories and for child subcategories.
So, my question is
1)
How can I exclude from the list of terms displayed on the button parent categories on child archives?
2)
Similarly I want to exclude child list of terms on parent category archives.
Thanks.
Hi there,
just to be clear, you do want to change what posts are displayed.. just the terms that each post has ?
Hi David,
Thank you very much for your answer.
I just want to change the terms that are displayed.
Ok, so it requires a custom function.
1. Add this PHP Snippet to your site:
// display custom terms in loop
// show only parent terms on parent archives
// show only child terms on child archives
function custom_get_terms() {
// set the taxonomy
$tax_name = 'category';
// is archive parent or child logic
$current_term = get_queried_object();
$is_parent = $current_term->parent == 0 ? true : false;
// get the terms
$terms = get_the_terms( get_the_ID(), $tax_name );
$html = '<ul class="custom-terms">';
foreach( $terms as $key => $term ) {
if ( ( $is_parent && $term->parent == 0 ) || ( !$is_parent && $term->parent != 0 ) ) {
// return html if term heirarchy matches archives
$html .= '<li><a href="' . esc_attr( get_term_link( $term->slug, $tax_name ) ) . '">' . __( $term->name ) . '</a></li>';
}
}
$html .= '</ul>';
return $html;
}
// render_block with class of custom-terms
add_filter( 'render_block', function( $block_content, $block ) {
if (
! empty( $block['attrs']['className'] )
&& 'custom-terms' === $block['attrs']['className']
) {
$block_content = custom_get_terms();
}
return $block_content;
}, 10, 2 );
2.Then in your element, add a headline block, with just some static text, and in Advanced > Additional CSS Class(es) add: custom-terms
3. It will require some CSS to remove bullets and display it as a row:
.custom-terms {
list-style: none;
margin-left: 0;
display: flex;
flex-wrap: wrap;
gap: 5px;
}
The font size and colors you can apply directly to the headline block.
Absolutly perfect!.
You guys are amazing!
Sincere thanks!
Glad to be of help