Force load 404 page

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?

If you run this logic at the controller level, rather than the view level, it should be much easier to return a 404.

Try to use the pre_get_posts action to set the 404 like so:

add_action('pre_get_posts', function (\WP_Query $query): void {
    if (// your logic to catch the endpoint) {
        $query->is_404 = true;
    }
});

Not 100% sure that’ll work but makes sense to me.

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