Drupalwoo ☉

Building a Custom Drupal Block for Related Tagged Content

A related-content block can keep visitors moving through a Drupal site by showing nodes that share taxonomy terms with the page they are reading. It is useful for news, documentation, recipes, events, product information and other content types where a tag describes a subject or theme.

Drupal provides Views for many recommendation lists, but a custom block gives developers tighter control over the query, output, caching and fallback behaviour. The example below uses a taxonomy reference field called field_tags and displays up to five published articles related to the current node.

This approach suits Australian publishers, community organisations and small businesses that want a lightweight feature without adding a large recommendation platform. It can also be adapted for a Melbourne events site, a Brisbane trade business, or a Perth retailer whose catalogue content is organised by product terms.

The implementation targets Drupal 10 and Drupal 11 conventions. It uses entity queries with access checking, rendered entity output and cache metadata, so the result remains manageable when editors update tags or when visitors browse from mobile connections across Australia.

Approach Best for Main advantage Limitation
Views block Standard lists and editor-managed displays Fast configuration and strong UI Less control over matching logic
Custom block plugin Precise tag matching and custom fallbacks Full control over query and rendering Requires PHP and module maintenance
Search API Large sites and relevance-based results Scalable indexing and ranking More configuration and infrastructure
External recommendations High-volume commercial sites Behaviour-based personalisation Cost, privacy and integration overhead

Why Use Tagged Recommendations

Tags provide a simple relationship between nodes. An article about drought-resistant gardens might share terms such as water saving, native plants and outdoor design with several other articles. The block can use any matching term, exclude the current node, and order the results by publication date.

This differs from manually selected references because editors do not need to maintain a list on every page. It also avoids relying on keyword searches, which can produce false matches when a word appears in body text without representing the subject. For a content team working between Sydney and Adelaide, a controlled vocabulary creates a more consistent editorial workflow.

The block should have a clear fallback policy. It can disappear when the current node has no tags, show a general list from the same content type, or display a short message for authenticated editors. On a public site, returning an empty render array is usually cleaner than exposing an empty heading.

Prepare the Custom Module

Create a module directory such as web/modules/custom/related_tag_block. The minimum files are related_tag_block.info.yml and a block plugin class. The module declaration can be kept small:

name: Related Tag Block
type: module
description: Displays published content sharing tags with the current node.
package: Custom
core_version_requirement: ^10 || ^11
dependencies:
  - drupal:node
  - drupal:taxonomy

Place the plugin at src/Plugin/Block/RelatedTagBlock.php. Drupal discovers the class from its namespace and block annotation. The constructor receives services through dependency injection instead of loading them statically, which makes the code easier to test and maintain.

The example assumes that field_tags is an entity reference field pointing to taxonomy terms. If the site uses field_topics, field_subjects or a field attached to a custom content type, change the field name in the class and adjust the content-type condition.

Read the Current Node

A block needs to identify the node shown by the current route. Injecting current_route_match is more reliable than reading the URL manually because it works with Drupal’s route system and keeps the plugin independent from path aliases.

<?php

namespace Drupal\related_tag_block\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\node\NodeInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Provides a related content block based on taxonomy tags.
 *
 * @Block(
 *   id = "related_tag_block",
 *   admin_label = @Translation("Related content by tags")
 * )
 */
final class RelatedTagBlock extends BlockBase implements ContainerFactoryPluginInterface {

  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    private readonly RouteMatchInterface $routeMatch,
    private readonly EntityTypeManagerInterface $entityTypeManager,
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
  }

  public static function create(
    ContainerInterface $container,
    array $configuration,
    $plugin_id,
    $plugin_definition,
  ): static {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_route_match'),
      $container->get('entity_type.manager'),
    );
  }

The first guard should confirm that the route parameter is a node and that the node has the expected tag field. This matters because the same block may be placed in a global region and therefore appear on taxonomy pages, search pages or custom routes.

  public function build(): array {
    $node = $this->routeMatch->getParameter('node');

    if (!$node instanceof NodeInterface || !$node->hasField('field_tags')) {
      return [];
    }

    $tag_ids = array_column(
      $node->get('field_tags')->getValue(),
      'target_id'
    );

    if (!$tag_ids) {
      return [];
    }

The target_id values are taxonomy term IDs. An empty field produces an empty array, allowing the block to stop before running an unnecessary database query. This is preferable to showing unrelated articles simply because a page has no editorial classification.

Query Matching Content Safely

Use Drupal’s entity query API rather than writing SQL directly. The query below finds published articles containing at least one of the current node’s terms, excludes the current node, and limits the result to five items.

    $storage = $this->entityTypeManager->getStorage('node');

    $ids = $storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'article')
      ->condition('status', 1)
      ->condition('field_tags.target_id', $tag_ids, 'IN')
      ->condition('nid', $node->id(), '<>')
      ->sort('created', 'DESC')
      ->range(0, 5)
      ->execute();

    if (!$ids) {
      return [];
    }

    $related_nodes = $storage->loadMultiple($ids);

accessCheck(TRUE) is important. It prevents the block from exposing restricted content to visitors who cannot view it. The status condition removes unpublished nodes, while the content-type condition avoids mixing press releases, landing pages or products into an article list by accident.

For multilingual sites, Drupal handles entity language negotiation during loading and rendering, but the site should still test translated tags. If term translations are important to the matching rules, consider using a language-aware indexing strategy or Search API. Also think about editorial freshness: a strict date sort is predictable, while a weighted query could prioritise pages with the greatest number of shared tags.

Render the Results and Cache Them

The entity view builder should render each node in the configured teaser mode. This preserves field formatters, image styles, language handling and access metadata. A theme can then style the list without duplicating node display logic in PHP.

    $view_builder = $this->entityTypeManager
      ->getViewBuilder('node');

    $items = [];
    foreach ($related_nodes as $related_node) {
      $items[] = $view_builder->view($related_node, 'teaser');
    }

    return [
      '#theme' => 'item_list',
      '#items' => $items,
      '#title' => $this->t('Related content'),
      '#cache' => [
        'contexts' => [
          'url.path',
          'languages:language_interface',
          'user.permissions',
        ],
        'tags' => [
          'node_list:article',
        ],
        'max-age' => 3600,
      ],
    ];
  }

}

The url.path context ensures that the block varies between node pages, while language and permissions account for common differences in output. The node view builder contributes additional cacheability metadata for each rendered entity. The node_list:article tag helps invalidate the list when article entities change; for highly dynamic sites, a custom cache service can add more precise tags.

A one-hour maximum age is a practical starting point for a publishing site. A newsroom posting frequently throughout the day may choose 15 minutes, while a stable documentation site could use several hours. Clear the Drupal cache after enabling the module or changing plugin annotations, then place the block in a region through the block layout screen.

Checks Before Publishing

Make the Block Useful for Editors

The block title should explain the relationship rather than expose an implementation detail. “Related content” works for most sites, while “More about this topic” may suit a public-facing magazine. Avoid titles such as “Tag query results”, which describe the code rather than the reader benefit.

Editors need consistent tagging guidance. A term such as Sydney may refer to a location, an audience or an event venue, so a controlled vocabulary and short descriptions reduce ambiguity. On a large Australian site, terms for states and territories should follow an agreed style, such as New South Wales rather than mixing NSW, New South Wales and suburb names.

The component should also work on narrow screens. Many visitors browse during commutes or between appointments, often using mobile devices on variable NBN, 4G or 5G connections. Keep thumbnails reasonably sized, avoid loading a large image for every recommendation, and make the entire title link easy to tap.

For a site publishing technical updates, related links can sit below the article body without interrupting the main task. Editors may also use Drupal code updates as a source of ideas for related implementation notes, provided external references are reviewed before publication.

Test, Secure and Maintain the Feature

Test the block with anonymous and authenticated accounts, because access permissions can change the result set. Create two nodes with a shared term, remove that term from one of them, unpublish another, and confirm that the block updates after cache invalidation. Also test a node with no tags and a route that is not a node page.

Use Drupal’s cacheability debugging headers in a development environment to inspect contexts and tags. Automated kernel tests can create nodes and taxonomy terms, render the block, and assert that the current node is excluded. A functional test can verify that the block is visible in the intended region and that the heading is accessible.

Australian sites should review privacy obligations when tags or recommendations could reveal sensitive interests. The Privacy Act 1988 and the Australian Privacy Principles are especially relevant if personal data, user profiles or behavioural tracking are later added. A simple editorial tag relationship generally avoids profiling, but analytics scripts and personalised recommendations require a separate assessment.

Final Quality Checks

A custom block is a small feature, but it touches routing, entity access, taxonomy, rendering and caching. Keeping each concern inside Drupal’s APIs produces a maintainable related-content component that editors can use without manually curating every recommendation.