- This topic has 1 reply, 2 voices, and was last updated 2 years, 11 months ago by
Ying.
-
AuthorPosts
-
March 23, 2023 at 9:17 am #2579048
John
Hello,
I’m trying to create a “related content” query loop in a Block element set to appear at the bottom of every blog post.
I have found how to use the GB query loop to set parameters as “current terms” and “include children terms”, but what I want to do is to pull content from the parent term (if there is one).
To illustrate, say my taxonomy has several terms, some of which have children terms:
Taxonomy
– Parent term 1
– Child term 1-1
– Child term 1-2
– Child term 1-3
– Parent term 2
– Child term 2-1
– Child term 2-2
– Child term 2-3
– Term 3
– Term 4When a post is tagged with the term “Child term 1-2” for example, I would like the query loop to pull any post that includes the “Parent term 1” term or any of its children.
Is there a way to achieve that?
March 23, 2023 at 11:08 am #2579200Ying
StaffCustomer SupportHi John,
This will require some custom coding, try the following steps:
1. Add a CSS class to the Grid block of the query loop, eg.
my-css-class.
https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/2. Add this PHP code, if your taxonomy is
category, you need to change thecategoryto the name of your taxonomy in the below code:add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) { if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-css-class' ) !== false ) { // Get current post's term $post_terms = get_the_terms( get_the_ID(), 'category' ); if ( ! empty( $post_terms ) ) { // Check if current term is a child term of a parent term $current_term = $post_terms[0]; if ( $current_term->parent != 0 ) { // Get parent term $parent_term = get_term( $current_term->parent, 'category' ); // Include parent term and all its child terms in the query $query_args['tax_query'][] = array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( $parent_term->term_id ), 'include_children' => true ); } else { // Include only current term in the query $query_args['tax_query'][] = array( 'taxonomy' => 'category', 'field' => 'term_id', 'terms' => array( $current_term->term_id ) ); } } } return $query_args; }, 10, 2 );Adding PHP: https://docs.generatepress.com/article/adding-php/
Let me know if this helps!
-
AuthorPosts
- You must be logged in to reply to this topic.