Query loop not showing post from same tag

Hi there,

I added a query loop to show related post based on tag, however posts from other tags shows up as well.

How do I only show related post from the same tag?

Thanks for your help.

Hi @venchy_123,

You can do so if you add my-class-name to the classlist of the Post Template Block of the Query Loop Block, then add this PHP snippet:

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-class-name' ) !== false ) {
        if ( is_single() && ! is_admin() ) {
           	$tag_values = array();
            $tags = get_the_tags();
            foreach ( $tags as $tag ) {
                $tag_values[] = $tag->slug;
            }
			$query_args['tax_query'] = array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => $tag_values,
            	),
        	);
			$query_args['post__not_in'] = [get_the_ID()];
			$query_args['orderby'] = 'rand';
       }
	   return $query_args;
    }

    return $query_args;
}, 10, 2 );

Adding PHP reference: Adding PHP - Documentation

Hope this helps!

Hello, @fernandoazarcon2 Tnx!

This code works fine for the related ones but all that code appears in the middle.

I see. I modified the code above. Can you try again?

@fernandoazarcon2 thank you for trying to help us!
Unfortunately, the code above doesn’t work for me at all.
You should also take into consideration that it’s causing PHP warnings in editor, when Element > Block is in edition.

I don’t understand what is that part for:

// Remove first category as long as there's more than 4 categories.
        if ( count( $tag_values ) > 1 ) {
            unset( $tag_values[0] );
        }

I see it’s about tags, not categories, but the condition checks if there are more than 1 tag, not 4.
I gave up this passage, and the snippet below doesn’t crash even the post has more than 4 tags or categories.

My working adaptation

It’s focused on tags, as they are more specific than categories, so there are more chances that related posts have similar content.
If no tags, then take categories into account.

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
	if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-class-name ) !== false ) {	
		if ( is_single() && ! is_admin() ) {
			if (has_tag()) {
				$tag_values = array();
				$tags = get_the_tags();
				foreach ( $tags as $tag ) {
					$tag_values[] = $tag->slug;
				}
				$tag_slug = implode( ', ', $tag_values );
				$query_args['tax_query'] = array(
					array(
						'taxonomy' => 'post_tag',
						'field' => 'slug',
						'terms' => $tag_values,
					),
				);
			} else {
				$cat_values = array();
				$cats = get_the_category();
	
				foreach ( $cats as $cat ) {
					$cat_values[] = $cat->slug;
				}
				$cat_slug = implode( ', ', $cat_values );
				$query_args['tax_query'] = array(
					array(
						'taxonomy' => 'category',
						'field' => 'slug',
						'terms' => $cat_values,
					),
				);
			}
		} 
	$query_args['post__not_in'] = [get_the_ID()];
	$query_args['orderby'] = 'rand';
	}
	return $query_args;
}, 10, 2 );

Random order isn’t boring, let’s say, but I’m not completely satisfied because:

  • Very old posts may appear (there’s no limit of time)
  • Older post may be displayed above the newer one

Hello, @fernandoazarcon2

Thank you very much. Great. It works for me. Now the behaviour is exactly the same as I was using with Wp Show Post per tag

As @Rafiozoo indicates the problem when editing the hook in Element continues, in my case I keep getting a critical error when trying to edit it.

I will look in the error log or I can even give you access to the staging admin to look at it if you want.

Thanks! I didn’t notice I forgot to place ! is_admin().

This code simply removes to first Category of the post if you don’t want it included in the “related posts”. It can be removed.:

if ( count( $tag_values ) > 1 ) {
            unset( $tag_values[0] );
        }

If you want to add a date parameter to exclude old posts, you can set a date_query. Example:

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-class-name' ) !== false ) {
        if ( is_single() && ! is_admin() ) {
           	$tag_values = array();
            $tags = get_the_tags();
            foreach ( $tags as $tag ) {
                $tag_values[] = $tag->slug;
            }
			$query_args['tax_query'] = array(
            array(
                'taxonomy' => 'post_tag',
                'field' => 'slug',
                'terms' => $tag_values,
            	),
        	);
			$query_args['post__not_in'] = [get_the_ID()];
			$query_args['orderby'] = 'rand';
			$query_args['date_query'] = array( array( 'after' => 'December 4th, 2021') );
       }
	   return $query_args;
    }

    return $query_args;
}, 10, 2 );

Just replace December 4th, 2021 with your preferred date.

Hope this helps!

Thanks for your help. It worked for me.

You’re welcome @venchy_123!