Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save khoand0000/ed6969a910caaeb7ab47 to your computer and use it in GitHub Desktop.
Save khoand0000/ed6969a910caaeb7ab47 to your computer and use it in GitHub Desktop.
  • My purpose: customize message after save post (post_type=at_order).
  • Solution: using admin_notices, redirect_post_location, post_updated_messages.
  • How: after saving post with post_type=at_order, redirect to /wp-admin/post.php?post=123&action=edit&message=1 --> wordpress will show message base on message parameter.
  • Case 1: I want to customize message (post_type=at_order) when message=1, using post_updated_messages filter.
function postUpdatedMessages($messages)
{
    $messages['at_order'][1] = __('blabla', AloThau::$text_domain); // change

    return $messages;
}

Case 2: Base on input (meta input) of user, I want to show error message instead success message, using save_post_at_order action, redirect_post_location filter, admin_notices action and using a variable to identify error code ($this->message_number).

  • In save_post_at_order action, assign $this->message_number when error condition occurs (=null means no error).
function savePostAtOrder($post_ID, $post, $update) 
{
    if ($error) {
      $this->message_number = 20;
    }
}
  • In redirect_post_location filter (the filter occurs after save_post_at_order action), replace message=1 to message=message_number if $this->message_number != null
function redirectPostLocation($location, $post_id)
{
    if ($this->message_number)
        $location = str_replace('message=1', 'message=' . $this->message_number, $location);
    return $location;
}
  • In admin_notices action (actually, it occurs before save_post_at_order action, but I make it is just triggered when message parameter >= 20, means error), base message value will show corresponding message text
public function __construct()
{
    if (isset($_GET['message']) && intval($_GET['message']) >= 20)
        add_action('admin_notices', [&$this, 'adminNotice']);
}
function adminNotice()
{
    $number = intval($_GET['message']);
    switch ($number) {
        case 20:
            $message = __('Error code is 20.', 'my_domain');
            break;
    }

    echo '<div class="error"><p>'.$message.'</p></div>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment