One way to accomplish this would be by using a service tagged with the path_processor_outbound
service tag.
Your service should then implement the processOutbound()
function in order to modify all links on a page, if the request delivers a node object of the type you want.
This is an example service definition using the described service tag:
services:
dummy.link_modifier_service:
class: Drupal\dummy\DefaultService
tags:
- { name: path_processor_outbound }
arguments: ['@request_stack']
This is an example implementation of such a service:
<?php
namespace Drupal\dummy;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Render\BubbleableMetadata;
/**
* Class DefaultService.
*/
class DefaultService implements DefaultServiceInterface, OutboundPathProcessorInterface {
/**
* Symfony\Component\HttpFoundation\RequestStack definition.
*
* @var \Symfony\Component\HttpFoundation\RequestStack
*/
protected $requestStack;
/**
* Constructs a new DefaultService object.
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
if (empty($request)) {
$request = $this->requestStack->getCurrentRequest();
}
$node = $request->attributes->get('node');
if ($node && $node->bundle() === 'product') {
$options['query'][] = [$node->bundle() . '_id' => $node->id()];
}
return $path;
}
}
This code will now be modifying all Drupal-handled URLs and adding a product_id=XX parameter to them.
Hope this helps, good luck!
@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21PathProcessor%21OutboundPathProcessorInterface.php/function/OutboundPathProcessorInterface%3A%3AprocessOutbound/