web-dev-qa-db-ja.com

保存/更新後に管理通知を追加する方法

Post-metaからアドレスを取得し、Google APIから緯度/経度の座標を取得するためにpost_saveを使用する投稿タイプがあります。座標の取得に問題があるかどうかをユーザーに通知する方法が必要です。 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は同じクラスの別の関数にあります。それはうまくいっています。

15
Jason

これがうまくいかないのは、save_postアクションの後にリダイレクトが発生しているためです。あなたが望むことを達成することができる一つの方法はquery varsを使って簡単な回避策を実行することです。

これを示すサンプルクラスは次のとおりです。

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
  }
}

これがあなたに少し役立つことを願っています。乾杯

29
jonathanbardo

このようなシナリオのためのラッパークラスを作りました。実際には、このクラスは通知を表示することを含むすべてのシナリオで使用できます。私は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.'));

通知が1回表示されます。

10
DarkNeuron

新しいページがロードされた後にquery引数を削除したいのであれば、@ jonathanbardoの優れた機能と優れた機能に加えて、 removed_query_args filterを使用することができます。あなたはあなた自身の引数を追加できる引数名の配列を取得します。それから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'
6
AncientRo

シンプルでエレガント、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>';
}
0
Fleuv