I have a certain case, hard to describe so I’ll show the code:
functions.php
Here I make sure all “subpages” load the projects page template. For example: mysite.com/projects/typeA shows the projects page.
add_rewrite_rule( '^projects\/(.*)\/?', "index.php?page_id=8", 'top' );
In the page-projects.blade.php template I test if the project type provided as subpage exist.
@php
$project_type_url = str_replace('/projects/', '', $_SERVER['REQUEST_URI']);
$project_types = get_posts( array( 'post_type' => 'projecttype', 'posts_per_page' => -1 ) );
$valid_url = false;
foreach( $project_types as $project_type ) :
if( $project_type->post_title === $project_type_url ) $valid_url = true;
endforeach;
@endphp
Above code works, if i go to mysite.com/projects/randomgibberish, $valid_url
is false
(as opposed to mysite.com/projects/typeA where it is true
).
Now I’d prefer to show the 404 template when the project type does not exist. I tried a few things, the only thing I could come up with that effectively works, is copying the 404 template’s content in page-project.blade.php inside an @if structure.
@extends('layouts.app)
@if ( !$valid_url )
404 template content
@else
projects template content
@endif
Is this the best approach to my problem?