deadlyhifi
deadlyhifi

Reputation: 607

apply_filters from within a Class (WordPress)

I'm writing a plugin that makes use of the wp_mail function. However I want to change the From: address. WP provides some filters - wp_mail_from_name and wp_mail_from - but I'm not sure how to call them from within a Class.

If I place them outside of a function there's a parse error (unexpected T_STRING, expecting T_FUNCTION).

If I place them within a function nothing seems to happen

class myPlugin {    
    public function setFromname($fromname) {
        apply_filters( 'wp_mail_from_name', $fromname );
        $this->fromname = $fromname;
    }
    public function setFromemail($fromemail) {
        apply_filters( 'wp_mail_from', $fromemail );
        $this->fromemail = $fromemail;
    }
}

How is it possible to affect these filters within a Class?

Upvotes: 3

Views: 2574

Answers (1)

radiok
radiok

Reputation: 93

In WordPress filters must have a call back, they can not use a variable.

class myPlugin {
    public function myPlugin {
        add_filter( 'wp_mail_from_name', array($this, 'filter_mail_from_name'));
        add_filter( 'wp_mail_from', array($this, 'filter_mail_from'));
    }

    function filter_mail_from_name( $from_name ) {
        // the $from_name comes from WordPress, this is the default $from_name
        // you must modify the $from_name from within this function before returning it
        return $from_name;
    }

    function filter_mail_from( $from_email ) {
        // the $from_email comes from WordPress, this is the default $from_name
        // you must modify the $from_email from within this function before returning it
        return $from_email;
    }
}

Upvotes: 3

Related Questions