WordPress – Create own admin messages for Custom Post Type

I’ve created a custom post type called routes and I’d like to be able to return error messages to the screen when something goes wrong during a save/update e.g. The type allows for gpx/kml files to be uploaded and checked that the correct type has been posted. At the moment it just returns if it goes wrong – how can I set an error message?

//Return if file type wrong.
if($file_type != 'application/octet-stream' && $file_type != 'application/gpx+xml' ) {
return;
}

Related posts

Leave a Reply

1 comment

  1. try this

    example:

    add_admin_message('Please enter valid URL for the project link', true);
    add_admin_message('Your custom post type was updated');
    

    source:

    <?php
    
    /**
     * Messages with the default wordpress classes
     */
    function showMessage($message, $errormsg = false)
    {
        if ($errormsg) {
            echo '<div id="message" class="error">';
        }
        else {
            echo '<div id="message" class="updated fade">';
        }
    
        echo "<p>$message</p></div>";
    }
    
    /**
     * Display custom messages
     */
    function show_admin_messages()
    {
        if(isset($_COOKIE['wp-admin-messages-normal'])) {
            $messages = strtok($_COOKIE['wp-admin-messages-normal'], "@@");
    
            while ($messages !== false) {
                showMessage($messages, true);
                $messages = strtok("@@");
            }
    
            setcookie('wp-admin-messages-normal', null);
        }
    
        if(isset($_COOKIE['wp-admin-messages-error'])) {
            $messages = strtok($_COOKIE['wp-admin-messages-error'], "@@");
    
            while ($messages !== false) {
                showMessage($messages, true);
                $messages = strtok("@@");
            }
    
            setcookie('wp-admin-messages-error', null);
        }
    }
    
    /** 
      * Hook into admin notices 
      */
    add_action('admin_notices', 'show_admin_messages');
    
    /**
     * User Wrapper
     */
    function add_admin_message($message, $error = false)
    {
        if(empty($message)) return false;
    
        if($error) {
            setcookie('wp-admin-messages-error', $_COOKIE['wp-admin-messages-error'] . '@@' . $message, time()+60);
        } else {
            setcookie('wp-admin-messages-normal', $_COOKIE['wp-admin-messages-normal'] . '@@' . $message, time()+60);
        }
    }