Home › Forums › General Issues › Add admin notices when using acf/update_value
I’m using the acf/update_value/name={$field_name} hook.
In the filter I am performing actions based on the submitted value.
I would like to add an admin notice to be displayed based on the action that was performed. However, it appears that using add_action('admin_notices', my_function);
when the action happens is too late and that this hook fired before my function was run.
Anyone know how to get my admin notice to work? Or if I can or can’t?
thanks,
~JH
Well, figured it out.
I forgot that the page would be redirected after the update so my hook, or any value I set would not be in effect….
If anyone is interested this is what I did.
Needed to add a temporary option value with update_option() then delete the value after displaying the admin notice.
Another way to accomplish this is to use the global variable $_SESSION to store whatever you want the notice to be. I wrote a PHP class and wrapper function to keep track of the notices so you don’t have to write to the database.
<?php
/**
* Class to handle admin notices
*
*/
class BricNotices {
public function __construct() {
//Start the session
add_action( 'admin_init', [ $this, 'start_session' ] );
add_action( 'admin_notices', [ $this, 'display_notices' ] );
}
/**
* Add a notice
*
*
*/
public function add_notice( $text = '', $type = 'success' ) {
$_SESSION['bric_notices'][] = [
'type' => $type,
'text' => $text,
];
}
/**
* Display the notices
*
*
*/
public function display_notices() {
if ( !isset( $_SESSION['bric_notices'] ) && empty( $_SESSION['bric_notices'] ) ) {
return;
}
if ( is_array( $_SESSION['bric_notices'] ) ) {
foreach ( $_SESSION['bric_notices'] as $this->notice ) {
$this->print_notice();
}
}
//Delete the notices
unset( $_SESSION[ 'bric_notices' ] );
}
private function print_notice() {
//notice types = error, warning, success, info
printf( '<div class="notice notice-%s is-dismissible"><p>%s</p></div>', $this->notice['type'], $this->notice['text'] );
}
/**
* Enable the use of the global $_SESSION variable
*
*
*
*/
public function start_session() {
if ( !isset( $_SESSION )) {
session_start();
}
}
}
global $BricNotices;
$BricNotices = new BricNotices();
function add_bric_notice( $text = '', $type = 'success' ) {
global $BricNotices;
$BricNotices->add_notice( $text, $type );
}
The topic ‘Add admin notices when using acf/update_value’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.