Conditional single post Bricks template based on internal referrer URL

In the BricksLabs Facebook group, a user asks:

Wonder:

Is it possible to automatically select a single post template depending on the page from which the post is accessed?

Example: My post “Opening ceremony” appears on the page “News” and on the page “Events”. If the user opens this post from the news page, template 1 should be selected automatically. If the user opens this post from the Events page, Template 2 should be selected automatically.

This Pro tutorial shows how bricks/active_templates filter can be used to show single posts in different Bricks templates for different pages based on the page URLs.

Step 1

Create three Bricks templates:

  • one for when the user visits any post from the /news page
  • another for when the user visits any post from the /events page
  • another default template

For the default template, make sure you set the template condition.

The other two should not have a template condition set.

Step 2

Add the following in child theme‘s functions.php (w/o the opening PHP tag) or a code snippets plugin:

<?php

add_filter( 'bricks/active_templates', function ( $active_templates, $post_id, $content_type ) {
    // Only run my logic on the frontend
    if ( ! bricks_is_frontend() ) {
        return $active_templates;
    }

    // Return if single post $content_type is not 'content'
    if ( $content_type !== 'content' ) {
        return $active_templates;
    }

    // Return: Current post type is not 'post'
    $post_type = get_post_type( $post_id );

    if ( $post_type !== 'post' ) {
        return $active_templates;
    }

    // Get the referrer URL
    $referer = wp_get_referer();

    if ( ! $referer ) {
        return $active_templates;
    }

    // URLs for News and Events pages
    $news_url = get_site_url() . '/news/';
    $events_url = get_site_url() . '/events/';

    // Check if the referer matches News or Events URL
    if ( $referer === $news_url ) {
        $active_templates['content'] = 237;
    } elseif ( $referer === $events_url ) {
        $active_templates['content'] = 240;
    }

  return $active_templates;
}, 10, 3 );

Replace 237 and 240 with the IDs of the corresponding Bricks templates.