What is the recommended way to save errors / warnings / user messages from actions / filters for custom display in the frontend?

This is a very basic question and there are a lot of solutions to it – however what is the recommended (or at least a good) way?

Problem statement: While processing a request to a WordPress project a lot of actions an filters are triggered. Some of those are defined in the template or some custom plugin and may fire messages / warnings / errors which will be needed in some custom output. What is the best way to save this errors for later displaying them to the user when the actual template is processed?

Have a look at the following (pseudo code) example:

Functions.php

function check_mail() {
if(filter_var($_POST[“email”],FILTER_VALIDATE_EMAIL)) {
save_mail($_POST[“email”];
} else {
save_error_for_template(“icmail”, new Error(“Incorrect Mail entered.”));
}
}

add_action(‘template_redirect’,’check_mail’);

custom-error-library.php

function save_error_for_template($key,$error) {
// save the error
}

function template_error_exists($key) {
// … straightforward
}

function get_template_error($key) {
// .. returns the error at $key
}

template-page.php

<form name=”subscribe”>
<input type=”email” value=”<?php echo $_POST[“email”]; ?>” />
<?php
if(template_error_exists(“icmail”)) {
?><p><?php echo get_template_error(“icmail”); ?></p><?php
}?>
</form>

Idea 1: Custom global variable (array) with errors

Pro: Always accessible
Contra: Requires the introduction of a custom global variable

Idea 2: add_option / get_option

Pro: Already implemented
Contra: Database access is slow, not sure if this integrates well with parallel processing / concurrency

Idea 3: ?

Read more here:: What is the recommended way to save errors / warnings / user messages from actions / filters for custom display in the frontend?

Leave a Reply

Your email address will not be published. Required fields are marked *