I made a plugin with a custom post type postcard
.
Most of postcards
are private.
I would like to redirect the logged out user in a specific php file inside my plugin instead of the 404.php
or achive.php
.
I tried with template_redirect
action like this :
add_action( "template_redirect", array( "MyClass", "is_redirection" ) );
Class MyClass{
public static function is_redirection(){
if( is_404() ) {
global $post_type;
if( $post_type === "postcard" ){
$templates_dir = get_current_plugin_templates_dir_path();
$page404 = $templates_dir . "/404-" . $post_type . ".php";
if ( file_exists( $page404 ) ) {
wp_redirect( $page404 );
exit;
}
}
}
}
}
My probleme here is $page404
is a file path, not an url so...
How can I do this wihtout using .htaccess
?
I made a plugin with a custom post type postcard
.
Most of postcards
are private.
I would like to redirect the logged out user in a specific php file inside my plugin instead of the 404.php
or achive.php
.
I tried with template_redirect
action like this :
add_action( "template_redirect", array( "MyClass", "is_redirection" ) );
Class MyClass{
public static function is_redirection(){
if( is_404() ) {
global $post_type;
if( $post_type === "postcard" ){
$templates_dir = get_current_plugin_templates_dir_path();
$page404 = $templates_dir . "/404-" . $post_type . ".php";
if ( file_exists( $page404 ) ) {
wp_redirect( $page404 );
exit;
}
}
}
}
}
My probleme here is $page404
is a file path, not an url so...
How can I do this wihtout using .htaccess
?
1 Answer
Reset to default 0This should work for you, using plugins_url()
:
...
// Assumes that your templates are in a subdirectory called 'templates' in your plugin.
// Adjust accordingly.
$templates_dir = plugins_url( 'templates', __FILE__ );
$page_404 = $templates_dir . '/404-' . $post_type . '.php' );
...
Update: template_include
If you want to have WordPress loaded up, you might be better off to use the template_include
filter.
add_filter( 'template_include', array( 'MyClass', '404_template' );
class MyClass {
function 404_template( $template ) {
if ( is_404() ) {
global $post_type;
$my_template = plugins_url( 'templates/404-' . $post_type . '.php' , __FILE__ );
if ( file_exists( $my_template ) ) {
$template = $my_template;
}
}
return $template;
}
}
get_current_plugin_templates_dir_path()
is -- I don't think it's a WordPress function. – Pat J Commented Aug 23, 2019 at 20:45get_current_plugin_templates_dir_path()
is just a function I did to get a path likefile-path-to-my-plugin-dir/front-end/templates/
– J.BizMai Commented Aug 23, 2019 at 20:51