保存/更新后如何添加管理员通知


16

我有一个帖子类型,使用post_save从帖子元中获取地址并从Google API中检索经/纬度坐标。我需要一种通知用户检索协调项是否存在问题的方法。我尝试使用admin_notices,但未显示任何内容:

public static function update_notice() {
  echo "<div class='error'><p>Failed to retrieve coordinates. Please check key and address.<p></div>";
  remove_action('admin_notices', 'update_notice');
}

add_action('admin_notices', array('GeoPost', 'update_notice'));

我不确定是否使用不正确或使用错误的上下文。需要明确的是,在实际代码中,add_action位于同一类的另一个函数中。很好


我开发了一个脚本,可让您轻松添加可解除/静态管理员通知github.com/askupasoftware/wp-admin-notification
Yoav Kadosh

Answers:


30

之所以不起作用,是因为在save_post操作之后发生了重定向。可以实现所需的一种方法是,通过使用查询变量来实现快速解决方案。

这是一个示例类来演示:

class My_Awesome_Plugin {
  public function __construct(){
   add_action( 'save_post', array( $this, 'save_post' ) );
   add_action( 'admin_notices', array( $this, 'admin_notices' ) );
  }

  public function save_post( $post_id, $post, $update ) {
   // Do you stuff here
   // ...

   // Add your query var if the coordinates are not retreive correctly.
   add_filter( 'redirect_post_location', array( $this, 'add_notice_query_var' ), 99 );
  }

  public function add_notice_query_var( $location ) {
   remove_filter( 'redirect_post_location', array( $this, 'add_notice_query_var' ), 99 );
   return add_query_arg( array( 'YOUR_QUERY_VAR' => 'ID' ), $location );
  }

  public function admin_notices() {
   if ( ! isset( $_GET['YOUR_QUERY_VAR'] ) ) {
     return;
   }
   ?>
   <div class="updated">
      <p><?php esc_html_e( 'YOUR MESSAGE', 'text-domain' ); ?></p>
   </div>
   <?php
  }
}

希望这对您有所帮助。干杯


效果很好,谢谢!但是第一行中缺少一个右括号(该行中有public function admin_notices()一个额外的右括号if ( ! isset(..
Rhys Wynne 2015年

我已经添加了,remove_query_arg('YOUR_QUERY_VAR');因为我发现它可以从上次更新中进行设置。
Tony O'Hagan

+1好答案。
标记

12

针对这种情况制作了包装器类。实际上,该类可以在涉及显示通知的任何情况下使用。我使用的是PSR标准,因此命名是非典型的Wordpress代码。

class AdminNotice
{
    const NOTICE_FIELD = 'my_admin_notice_message';

    public function displayAdminNotice()
    {
        $option      = get_option(self::NOTICE_FIELD);
        $message     = isset($option['message']) ? $option['message'] : false;
        $noticeLevel = ! empty($option['notice-level']) ? $option['notice-level'] : 'notice-error';

        if ($message) {
            echo "<div class='notice {$noticeLevel} is-dismissible'><p>{$message}</p></div>";
            delete_option(self::NOTICE_FIELD);
        }
    }

    public static function displayError($message)
    {
        self::updateOption($message, 'notice-error');
    }

    public static function displayWarning($message)
    {
        self::updateOption($message, 'notice-warning');
    }

    public static function displayInfo($message)
    {
        self::updateOption($message, 'notice-info');
    }

    public static function displaySuccess($message)
    {
        self::updateOption($message, 'notice-success');
    }

    protected static function updateOption($message, $noticeLevel) {
        update_option(self::NOTICE_FIELD, [
            'message' => $message,
            'notice-level' => $noticeLevel
        ]);
    }
}

用法:

add_action('admin_notices', [new AdminNotice(), 'displayAdminNotice']);
AdminNotice::displayError(__('An error occurred, check logs.'));

该通知仅显示一次。


6

除了@jonathanbardo的答案很好而且功能很好之外,如果要在加载新页面后删除查询参数,则可以使用removable_query_args过滤器。您将获得一个参数名称数组,可以在其中附加自己的参数。然后,WP将负责从URL中删除列表中的所有参数。

public function __construct() {
    ...
    add_filter('removable_query_args', array($this, 'add_removable_arg'));
}

public function add_removable_arg($args) {
    array_push($args, 'my-query-arg');
    return $args;
}

就像是:

'...post.php?post=1&my-query-arg=10'

会变成:

'...post.php?post=1'

1

基于的简单,优雅get_settings_errors()

function wpse152033_set_admin_notice($id, $message, $status = 'success') {
    set_transient('wpse152033' . '_' . $id, [
        'message' => $message,
        'status' => $status
    ], 30);
}

function wpse152033_get_admin_notice($id) {
    $transient = get_transient( 'wpse152033' . '_' . $id );
    if ( isset( $_GET['settings-updated'] ) && $_GET['settings-updated'] && $transient ) {
        delete_transient( 'wpse152033' . '_' . $id );
    }
    return $transient;
}

用法

在您的帖子请求处理程序中:

wpse152033_set_admin_notice(get_current_user_id(), 'Hello world', 'error');
wp_redirect(add_query_arg('settings-updated', 'true',  wp_get_referer()));

您想在其中使用管理通知的位置,通常在admin_notices挂钩中。

$notice = $this->get_admin_notice(get_current_user_id());
if (!empty($notice) && is_array($notice)) {
    $status = array_key_exists('status', $notice) ? $notice['status'] : 'success';
    $message = array_key_exists('message', $notice) ? $notice['message'] : '';
    print '<div class="notice notice-'.$status.' is-dismissible">'.$message.'</div>';
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.