E
E
Eugene2018-10-22 22:43:43
WordPress
Eugene, 2018-10-22 22:43:43

How to display notifications in the admin panel when saving a wordpress page?

Hey! I need to display a message in the wordpress admin when I save the page, I found a great class example, but I can't get it to work, here is the sample code
inc/notice.php

<?php
/**
 * OPC Notice
 *
 */
defined( 'ABSPATH' ) or die( 'You shall not pass!' );
if ( ! class_exists( 'OPC_Notice' ) ):
class OPC_Notice {
  /**
   * Message to be shown
   */
  private $message;
  /**
   * CSS classes to apply on the notice div
   */
  private $css_classes = array( 'notice' );
  /**
   * Magic starts here.
   *
   * @param  string  $message      Message to be shown
   * @param  array   $css_classes  CSS classes to apply on the notice div
   *
   * @since 1.0.6
   * @return void
   */
  public function __construct( $message, $css_classes ) {
    $this->message = $message;
    if( ! empty( $css_classes ) && is_array( $css_classes ) ) {
      $this->css_classes = array_merge( $this->css_classes, $css_classes );
    }
      error_log('1');
    add_action( 'admin_notices', array( $this, 'display_admin_notice' ));
  }
  /**
   * Displays admin notice on success, error, warning, etc.
   *
   * @since 1.0.6
   * @return void
   */
  public function display_admin_notice() {
        error_log('2');
    ?>
    <div class="<?php echo implode( ' ', $this->css_classes ); ?>">
      <p><?php echo $this->message; ?></p>
    </div>
    <?php
  }
}
endif;

init.php
....
require_once 'inc/notice.php';
require_once 'inc/metaboxes.php';
....

inc/metaboxes.php
class onpageconversionalatMetabox {
...
public function __construct() {
...
 add_action( 'save_post', array( $this, 'call_opc_api'), 20, 1);
}

public function call_opc_api ( $post_id ) {
...
... new OPC_Notice($user_notice_activate, array( 'notice-error', 'is-dismissible' ));
}
}

When saving a post, the log shows 1, but the message is not displayed. what am I doing wrong ?
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pychev Anatoly, 2018-10-23
@pton

But the number 2 is not displayed in the log, right?
It seems that at the time the "admin_notices" event occurs, your "OPC_Notice" class has not yet been created.
Try connecting an event handler to the "onpageconversionalatMetabox" class before the "save_post" handler and output the value 3 to the log and see which will be 3 or 1 earlier. If earlier will be 3, then my guess is correct, otherwise you have to dig. If 3 is not displayed at all, then the "onpageconversionalatMetabox" class is created late.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question