0

I have class:

 class users{

        public function __construct(){

           add_action('do_redirect', 'redirect'); 

        }

        public function redirect(){
                $url = get_site_url(null, '/welcome', 'https');  
                wp_redirect( $url );
                exit;
            }  

        public function some_function(){
        do_action('do_redirect');

    }

}

I get error :

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'redirect' not found or invalid function name.

If I use only wp_redirect() i get error for headers.

How i must change this, because i fell I do something wrong?

  • Take a look at the following answer wordpress.stackexchange.com/questions/48085/…. It explains how to call add_action with class methods. – czerspalace Mar 22 at 23:27
  • I change to "add_action('do_redirect',array( $this, 'redirect' ));" and works but now i still headers error – polyman Mar 22 at 23:59
  • Maybe you take a look here. Btw error with headers? what kind of error, what does it say. Please don't expect us to guess what errors you get, show them by adding them to your question (please update also the code now with your correction) – Charles Mar 23 at 0:34
  • At what point are you initiating the users class, or calling new users()? – czerspalace Mar 23 at 0:53
  • I have warning: Warning: Cannot modify header information - headers already sent by (output started at C:\Program Files\VertrigoServ\www\wp-includes\class.wp-styles.php:242) in C:\Program Files\VertrigoServ\www\wp-includes\pluggable.php on line 1251 – polyman Mar 23 at 9:58
0

When you're inside a class, you need to pass a reference to WordPress for WordPress to call the function within the class. See the line that contains $this.

class My_Users {
    public function __construct() {
        add_action( 'do_redirect', array( $this, 'redirect' ) );
    }

    public function redirect() {
        $url = get_site_url( null, '/welcome', 'https' );
        wp_safe_redirect( $url );
        exit;
    }


    public function some_function() {
        do_action( 'do_redirect' );
    }
}
$custom_users = new My_Users();
$custom_users->some_function();

That being said, you do not need to use an action here. It would be simpler to just do the following:

class My_Users {
    public function redirect() {
        $url = get_site_url( null, '/welcome', 'https' );
        wp_safe_redirect( $url );
        exit;
    }
}
$custom_users = new My_Users();
$custom_users->redirect();

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.