Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Display posts of same category as post

  • Hello,
    I am trying to create a sidebar block to display posts from the same category. I have tried using the ‘Inherit Query from Template’ but this results in a blank list.
    I am also trying the following from previous posts but i cannot see an option with ‘current post’ it is just a list of all the posts.
    Many Thanks


    in the block settings sidebar Parameters > Add New Parameter of:

    Taxonomy > Category and set the Terms to Current Post Terms.

    This will set the query loop to display posts that have the same category terms as the current post.

  • Hi there,

    do you have GeeneateBlocks Pro or just the free version ? As the current post arg is only present in GB Pro.
    Without pro it would require some PHP.

    Let me know

  • ah, yes, you are right, I have just realised I only have GP premium, not GB pro

  • Ok, with the free version you can add category related posts using the query loop like so.

    1. Add this PHP Snippet to your site:

    
    add_filter('generateblocks_query_loop_args', function ($query_args, $attributes) {
        if (
            !is_admin() && is_single() && 
            !empty($attributes['className']) && 
            strpos($attributes['className'], 'related-category') !== false
        ) {
            $current_post_id = get_the_ID();
            $current_post_categories = get_the_terms($current_post_id, 'category');
    
            if ($current_post_categories && !is_wp_error($current_post_categories)) {
                $category_ids = wp_list_pluck($current_post_categories, 'term_id');
    
                if (!empty($category_ids)) {
                    $additional_args = array(
                        'category__in' => $category_ids,
                        'post__not_in' => array($current_post_id),
                    );
    
                    $query_args = array_merge($query_args, $additional_args);
                }
            }
        }
    
        return $query_args;
    }, 10, 2);
    

    2. set up your query loop parameters so it just has the Post type set to Post, and the number of posts per page set. And no other parameters.

    3. select the Grid Block inside your query loop and give it an Advanced > Additional CSS Class of: related-category

  • great thanks

  • You’re welcome

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