0

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'm not sure what get_current_plugin_templates_dir_path() is -- I don't think it's a WordPress function. – Pat J Aug 23 at 20:45
  • get_current_plugin_templates_dir_path() is just a function I did to get a path like file-path-to-my-plugin-dir/front-end/templates/ – J.BizMai Aug 23 at 20:51
0

This 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;
    }
}
  • The redirection woks in your case but, without loading the wordpress core. For example : defined( 'ABSPATH' ) || exit; inside 404-postcard.php executes exit. Maybe there is a way to overwrite the 404 file path before running $wp_query->set_404(); – J.BizMai Aug 23 at 21:15
  • Instead of using the template_redirect action hook, you might be better suited by using the template_include filter. See my update. – Pat J Aug 23 at 21:31
  • is_404() return false at this moment :/, template_include seems to be earlier. – J.BizMai Aug 23 at 23:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.