Query block – don’t display current post

  • I have a news category setup for posts, and after the post, I want to display a continue reading section to display 3 more posts in this category. I set this up using a Query block in a block element, but I could not get the query block to skip the current post. Although I set the category and specified exclude current post in the query block, I couldn’t get it to work. The query block skpped the current post but displayed a post that was not in the news category I had specified.

    After doing much research, I found this code snippet which appears to work, and I set the ID for the news category in this snippet:

    add_filter( ‘generateblocks_query_loop_args’, function( $query_args, $attributes ) {
    // Intercept our targeted Query Block using its custom class name
    if ( ! empty( $attributes[‘className’] ) && strpos( $attributes[‘className’], ‘strict-single-category-exclude’ ) !== false ) {

    // 1. SAFE EXCLUSION: Pull the ID of the article currently being read
    $current_post_id = get_the_ID();
    if ( $current_post_id ) {
    $query_args[‘post__not_in’] = isset( $query_args[‘post__not_in’] ) ? (array) $query_args[‘post__not_in’] : array();
    $query_args[‘post__not_in’][] = $current_post_id;
    }

    // 2. STRICT TAXONOMY QUERY: Force GenerateBlocks to fetch only from the news category which has an id of 295
    $query_args[‘tax_query’] = array(
    array(
    ‘taxonomy’ => ‘category’,
    ‘field’ => ‘term_id’,
    ‘terms’ => array( 295 ),
    ‘operator’ => ‘IN’,
    ),
    );

    }

    return $query_args;
    }, 10, 2 );

    My question is this: Is this the correct way to set this up? Why doesn’t the query block allow me to set a category but exclude the current post? It seems to require this php snippet to get it to work.

  • Hi there,

    I don’t think you need this snippet.

    The post you linked requires username and password, i can not view it.

    Can you provide an admin login so I can check the query settings?

  • I would prefer to not use it.

    Here’s the information to access the staging site at https://dcbloxstg.wpengine.com/

    [credential removed by admin]

    The element is News Posts Continue Reading. The php snippet I added is called Continue Reading Section for News Posts

  • It requires 2FA when trying to logging WP admin.
    Can you disable that for now?

  • I disabled it. You should be able to login now.

  • I’ve removed the class from the query block (so the code no longer works for it) and configured the parameters to exclude the current post and restrict the category to news. Can you check if it’s displaying the correct posts?

  • Yes that works! Thank you!

  • No Problem 🙂

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