I cannot display an admin message by sending an argument to the function. It was suggested I use a closure function but this does not appear to work. Here is the code
function custom_woocommerce_admin_notice( $message ) {
add_action( 'admin_notices', function() use ( $message ) {
wc_get_logger()->info('Order Message: '.$message ) ;
if ( function_exists( 'get_current_screen' ) ) {
$screen = get_current_screen();
if ( isset( $screen->id ) && $screen->id === 'edit-shop_order' ) {
// Check if the notice has already been dismissed
if ( ! get_option( 'custom_woocommerce_admin_notice_dismissed' ) ) {
?>
<div class="notice notice-success is-dismissible woocommerce-notice">
<p><?php _e( 'Hello: '.$message , 'text-domain' ); ?></p>
</div>
<?php
}
}
}
});
}
add_action( 'admin_notices', 'custom_woocommerce_admin_notice' );
function custom_woocommerce_admin_notice_dismissed() {
update_option( 'custom_woocommerce_admin_notice_dismissed', 1 );
}
add_action( 'wp_ajax_custom_woocommerce_admin_notice_dismissed', 'custom_woocommerce_admin_notice_dismissed' );
function enqueue_custom_woocommerce_admin_notice_script( $hook ) {
// Check if we are on the WooCommerce orders page
if ( function_exists( 'get_current_screen' ) ) {
$screen = get_current_screen();
if ( isset( $screen->id ) && $screen->id === 'edit-shop_order' ) {
wp_enqueue_script( 'custom_woocommerce_admin_notice_script', get_template_directory_uri() . '/js/custom-woocommerce-admin-notice.js', array( 'jquery' ), null, true );
}
}
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_woocommerce_admin_notice_script' );
The function is called using
custom_woocommerce_admin_notice( $message );
Any ideas what is wrong? Without the closure function and not passing the $message variable and using a string it works.
For completeness here is the js script
jQuery(document).ready(function($) {
$('.notice.is-dismissible').on('click', '.notice-dismiss', function() {
$.ajax({
url: ajaxurl,
type: 'POST',
data: {
action: 'custom_woocommerce_admin_notice_dismissed'
}
});
});
});