Use GB query loop for Related Post

Hi @jrmora,

Can you try updating to GB version 1.5.0-rc.2 and see how it goes?: GenerateBlocks 1.5 - Dynamic Data, Query Loops, & Image Blocks - GenerateBlocks

Hi, @fernandoazarcon2

I upgraded to rc.2 and it didn’t fix it, this is the error log:

URL: staging.jrmora.com
WordPress versión 6.0
Active Theme: GeneratePress Child (versión 0.1)
PHP versión 8.1.1

Error details:

Se ha producido un error del tipo E_ERROR en la línea 303 del archivo public_html/staging/wp-content/themes/generatepress_child/functions.php. Mensaje de error: Uncaught TypeError: count(): Argument #1 ($value) must be of type Countable|array, WP_Error given in public_html/staging/wp-content/themes/generatepress_child/functions.php:303

Stack trace:
#0 public_html/staging/wp-includes/class-wp-hook.php(309): {closure}()
#1 public_html/staging/wp-includes/plugin.php(191): WP_Hook->apply_filters()
#2 public_html/staging/wp-content/plugins/generateblocks/includes/class-render-blocks.php(417): apply_filters()
#3 public_html/staging/wp-content/plugins/generateblocks/includes/class-render-blocks.php(317): GenerateBlocks_Render_Block->do_post_template()
#4 public_html/staging/wp-includes/class-wp-block.php(255): GenerateBlocks_Render_Block->do_grid_block()
#5 public_html/staging/wp-includes/class-wp-block.php(241): WP_Block->render()
#6 public_html/staging/wp-includes/blocks.php(901): WP_Block->render()
#7 public_html/staging/wp-includes/blocks.php(939): render_block()
#8 public_html/staging/wp-includes/class-wp-hook.php(307): do_blocks()
#9 public_html/staging/wp-includes/plugin.php(191): WP_Hook->apply_filters()
#10 public_html/staging/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php(1811): apply_filters()
#11 public_html/staging/wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php(560): WP_REST_Posts_Controller->prepare_item_for_response()
#12 public_html/staging/wp-includes/rest-api/class-wp-rest-server.php(1143): WP_REST_Posts_Controller->get_item()
#13 public_html/staging/wp-includes/rest-api/class-wp-rest-server.php(990): WP_REST_Server->respond_to_request()
#14 public_html/staging/wp-includes/rest-api.php(519): WP_REST_Server->dispatch()
#15 public_html/staging/wp-includes/rest-api.php(2868): rest_do_request()
#16 [internal function]: rest_preload_api_request()
#17 public_html/staging/wp-includes/block-editor.php(601): array_reduce()
#18 public_html/staging/wp-admin/edit-form-blocks.php(75): block_editor_rest_api_preload()
#19 public_html/staging/wp-admin/post.php(187): require(’ …’)
#20 {main}
thrown

Hi, is there any news about these two issues ?

  1. When a post has 2 category terms, it’s not displaying any related posts.
  1. It’s displaying same related posts for all posts in same category. Would it be possible to have something more “random” ?

Thanks !

1 Like

Hi!
I’ve tried the snippet above.
1st: Current post should be excluded.
2nd: Any chances to develop some more clever algorithm?
incorporate filtering also by tags?
(the more common tags - the higher index)

2 Likes

This snippet is good, but like others I am in need of 2 more features.

  1. Ability to exclude the current post
  2. Ability to order by ‘Random’

Any chance the snippet could be updated to include these features?

Also, are these features coming to Generate Blocks Pro?

Hello there,

To exclude the post and order the posts randomly, you’ll just need to add these lines:

$query_args['post__not_in'] = [get_the_ID()];
$query_args['orderby'] = 'rand';

For instance, the code would now be:

add_filter( 'generateblocks_query_loop_args', function( $query_args, $attributes ) {
    if ( ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'my-class-name' ) !== false ) {
        if ( is_single() ) {
            $cat_values = array();
            $cats = get_the_category();

            foreach ( $cats as $cat ) {
                $cat_values[] = $cat->slug;
            }
        } else {
            $cat_values = get_category( get_query_var( 'cat' ) );
        }

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

        $cat_slug = implode( ', ', $cat_values );
        $query_args['tax_query'] = array(
            array(
                'taxonomy' => 'category',
                'field' => 'slug',
                'terms' => $cat_slug,
            ),
        );
	$query_args['post__not_in'] = [get_the_ID()];
	$query_args['orderby'] = 'rand';
	
    }

    return $query_args;
}, 10, 2 );

Hope this helps!

1 Like

For tags, see my response here: Query loop not showing post from same tag - #2 by fernandoazarcon2

The code there excludes the current post as well.

Hope this helps

Hello, @fernandoazarcon2

Thank you very much for the new code.

Now it works perfect for me (but only random).
You can check it at https://staging.jrmora.com.

The only problem is the problem described here, which continues.

In order to edit the hook I have to remove the code from functions.php and put it back later.

Now I just need to get it squared up like in Wp Show Post XD to be able to remove WP Show Post. XD

Hi @fernandoazarcon2,

Thanks but it does not fix my two issues :

  1. When a post has 2 category terms, it’s not displaying any related posts.
  2. It still displaying always the same 4 posts in every posts of same category term. Random does not seems to work.

Thanks for your help,
Samuel

I am experiencing the same thing. Excluding the current post is working! Thank you!
Random ordering is not working.

I see. @Samlaflam and @brendenjj can you try this?:

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() ) {
           	$cat_values = array();
            $cats = get_the_category();

            foreach ( $cats as $cat ) {
                $cat_values[] = $cat->slug;
            }
			$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;
    }

    return $query_args;
}, 10, 2 );

Hope this helps!

Thanks @fernandoazarcon2,

Unfortunately, Random stil does not work. I still have always the same related post displaying for all posts in same category term.

But the problem regarding related posts not displaying if post has 2 category terms is fixed !

The posts do show them randomly, but if you have a wordpress cache plugin, it won’t show other related posts until the cache is refreshed.
The problem is not the code but the cache.

1 Like

Yes, as advised by @dmata, can you try clearing your cache?

Yes, that was it, sorry about that @fernandoazarcon2

But there is two problems here.

1/ The idea with the random option was at first to make related posts display randomly when the function is deployed, but then posts need to stay the same for SEO.

I don’t know if I’m making myself clear : Once posts have been displayed (randomly), they must remain the same in order to let the internal linking take place. If posts change each time the page is refreshed it is not good in terms of SEO. With WPSP and Tom’s function it worked well.

2/ It seems that you’ve removed the part that permits to remove first category as long as there’s more than 4 posts in sub-categories. Would it be possible to put it back ?

Thanks again

For me it is now working exactly as I used to use it with WP Show Post, I have even moved it to production and uninstalled WPSP.

I’m passing you the PHP warning that appears in error_log in case this helps to solve the Element filter editing problem.

[04-Jul-2022 08:32:05 UTC] PHP Warning: foreach() argument must be of type array|object, bool given in /public_html/wp-content/themes/generatepress_child/functions.php on line 303

Line 303 corresponds to this line of function code:

foreach ( $tags as $tag ) {

  1. WPSP random should work in the same way. It should be display posts randomly every time, not just one time. I’m thinking you had that site cached?

  2. Here’s a a version of that code back:

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() ) {
           	$cat_values = array();
            $cats = get_the_category();

            foreach ( $cats as $cat ) {
                $cat_values[] = $cat->slug;
            }
// Remove first category as long as there's more than 4 categories.
        if ( count( $cat_values ) > 1 ) {
            unset( $cat_values[0] );
        }

	    $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;
    }

    return $query_args;
}, 10, 2 );

Hi, from now on, I’m talking about things that are happening without any cache activated. My WPSP’s related posts are not changing when a page is refreshed and never have been.

Now I can tell you that both codes you’ve proposed have different behaviour:

The one without the “remove first category” part is displaying random related post from main category and it changes each time page is refreshed.

The one with the “remove first category” part is displaying always same related post (no random) from sub-category and it doesn’t change when page is refreshed.

Do you think it would be possible to have a combination of both ? Something like has been possible with WPSP : displaying random related posts first time and then keep it like that even when page is refreshed ?

I tried this code, but I am getting the same results. I get posts from the same category excluding the current post, but they are ordered by post date instead of randomly so all of the posts show the same 4 related posts. This is a development site so I do not have caching enabled.

To clarify, are you referring to this?: Edit List “my test” ‹ fazar...

By default, setting that to random should work as such when the page is refreshed: Screen Recording 2022-07-06...

Kindly let us know.