Roots Discourse

Including a Blade template through an action in functions.php/Setup.php

Using Blade 9.

I’m trying to get a page to be rendered with a certain template-file, based on the URL (a kind of dynamic route I guess?). I found and adapted a piece of code, which I added to my functions.php.

This loads the file, however, since it’s a blade.php-file, it’s not compiled and all the @-things (@extends, @section etc.), are just output as a string.
The output is literally as follows:
@extends('layouts.app') @section('content') IT WORKS! Dracula@endsection

This is my action:

add_action('init', function() {
  $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
  if ( strpos($url_path, 'arkiv/') !== false ) {
     // load the file if exists
     $load = locate_template('views/partials/archive-event-single.blade.php', true);
     if ($load) {
        load_template($load);
        exit();
     }
  }
});

Now, I have found out (but maybe misunderstood) that if I use include \App\template_path($load); it should work, but that just results in the same output, plus an added critical wordpress error.

So the include is working (since the content is still there), but it’s also resulting in a critical wordpress error.

I am considering just adding all the parts in as normal PHP, but that will totally kill the idea of Blade-files imo, so I rather not. Here is the content of the template file:

@extends('layouts.app')

@section('content')

  IT WORKS!
  <?php 
    $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
    $slug = str_replace('arkiv/', '', $url_path);
  ?>
  
@endsection

I’m open for different solutions as well, as long as I get Wordpress to render a page with a specific template, if the URL contains arkiv.

Thank you in advance!

I have actually solved it by creating a filter that returns the template, instead of load, making being rendered by Blade as if it’s any other template-file.
This is my code:

function single_event_template( $template ) {
    $url_path = trim(parse_url(add_query_arg(array()), PHP_URL_PATH), '/');
    if ( strpos($url_path, 'arkiv/') !== false  ) {
        $new_template = locate_template( 'views/partials/archive-event-single.blade.php' );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }
    return $template;
}

add_filter( 'template_include', 'single_event_template', 99 );

Still using the same way to check what page I’m on, but not loading the template anymore, but making sure the page thinks that this is THE template it wants to run.

This topic was automatically closed after 42 days. New replies are no longer allowed.