Skip to content
\n

The class contains various public methods that are being resolved to subcommands as expected. A reduced example:

\n
class MyCommandClass {\n    public function send_email(): void\n    {\n        wp_mail(\n            $_ENV['LOGGER_MAIL_TO'],\n            \"Hello there!\",\n            \"Hello again :)\",\n        );\n    }\n}
\n

Now I need to overwrite the from header in this email. I'm using the filter wp_mail_from for this. But now the callback function is being listed as a subcommand, since it needs to be public (due to the way WP filters work):

\n
class MyCommandClass {\n    public function send_email(): void\n    {\n        add_filter('wp_mail_from', [$this, 'wp_mail_from']);\n        wp_mail(\n            $_ENV['LOGGER_MAIL_TO'],\n            \"Hello there!\",\n            \"Hello again :)\",\n        );\n        remove_filter('wp_mail_from', [$this, 'wp_mail_from']);\n    }\n    /**\n     * Overwrite wp_mail_from\n     */\n    public function wp_mail_from(): string\n    {\n        return $_ENV['LOGGER_MAIL_FROM'];\n    }\n}
\n

On the shell I now get this:

\n
❯ wp my-command\nusage: wp my-command send_email\n   or: wp my-command wp_mail_from # I don't want this!
\n

Is there a way to hide the filter callback wp_mail_from from WP_CLI?

","upvoteCount":1,"answerCount":1,"acceptedAnswer":{"@type":"Answer","text":"

If you're not opposed to a closure, I think this could work.

\n
\\WP_CLI::add_command('my-command', 'MyCommandClass' );\n\nclass MyCommandClass {\n\tpublic function send_email(): void\n\t{\n\t\t$wp_mail_from = function(): string {\n\t\t\treturn $_ENV['LOGGER_MAIL_FROM'];\n\t\t};\n\t\tadd_filter('wp_mail_from', $wp_mail_from );\n\t\twp_mail(\n\t\t\t$_ENV['LOGGER_MAIL_TO'],\n\t\t\t\"Hello there!\",\n\t\t\t\"Hello again :)\",\n\t\t);\n\t\tremove_filter('wp_mail_from', $wp_mail_from );\n\t}\n}\n
","upvoteCount":1,"url":"https://github.com/orgs/wp-cli/discussions/5754#discussioncomment-5447288"}}}
Discussion options

You must be logged in to vote

If you're not opposed to a closure, I think this could work.

\WP_CLI::add_command('my-command', 'MyCommandClass' );

class MyCommandClass {
	public function send_email(): void
	{
		$wp_mail_from = function(): string {
			return $_ENV['LOGGER_MAIL_FROM'];
		};
		add_filter('wp_mail_from', $wp_mail_from );
		wp_mail(
			$_ENV['LOGGER_MAIL_TO'],
			"Hello there!",
			"Hello again :)",
		);
		remove_filter('wp_mail_from', $wp_mail_from );
	}
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@hirasso
Comment options

Answer selected by hirasso
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants