I am working on a plug-in for my personal site and I would like it have a certain permalink structure (/projects/project-type/sub-type/project). To achieve this, I am using the request
filter.
Inside my hook method, I am checking to make sure that the taxonom(y|ies) (project_type) exists before I load the post type (project). If it does not, the filter throws a 404 error and loads the theme's error template instead of just showing the project. Is it safe to do this?
public function request( $request ) {
$dummy_query = new \WP_Query();
$dummy_query->parse_query( $request );
if ( ! $dummy_query->is_admin && isset( $request['project_type'] ) ) {
$last_segment = basename( $request['project_type'] );
if ( false === get_term_by( 'slug', $last_segment, 'project_type' ) ) {
$types = explode( '/', substr( $request['project_type'], 0, strrpos( $request['project_type'], '/' ) ) );
foreach( $types as $type ) {
if ( false === get_term_by( 'slug', $type, 'project_type' ) ) {
header( 'HTTP/1.0 404 Not Found' );
locate_template( array( '404.php' ), true, true );
exit;
}
}
$request['post_type'] = 'project';
$request['project'] = $last_segment;
$request['name'] = $last_segment;
}
}
return $request;
}
This code was modified from this answer.