Site logo

[Support request] Query Loop pulling any term from parent term?

Home Forums Support [Support request] Query Loop pulling any term from parent term?

Home Forums Support Query Loop pulling any term from parent term?

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #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 4

    When 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?

    #2579200
    Ying
    Staff
    Customer Support

    Hi 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 the category to 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!

Viewing 2 posts - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.