1

When saving a post, i have a meta box in which the user must put something. If the user input is something when i do not accept, how will i tell him?

add_action('save_post' , 'my_save_metaboxe_data');

function my_save_metaboxe_data( $post_id )
{
    ....
    if ( 'something not accepted' )
    {
        return ????? ;
    }
    ....
}

I also read this post.

I personally just write a return; , but the most important problem i face in this way is it returns the following message to the user:

enter image description here

What can i do to prevent this message?

I have also studied the wonderful hook admin_notices, but i still do not know how to use it to appear when it should be.

So how can i prevent at least the above message? ( I develop a plugin for WordPress. )

My question is specific about creating a new custom post and for the meta boxes validations who i have added. How to handle the save_post action to return the appropriate messages and not always returning "everything going well".

0

Handling admin notice on Edit Post

When action related to post or editpost, we will be faced with redirect_post function. There are two filters you can use to handle the post messages, redirect_post_location and post_updated_messages ( see the list messages at https://core.trac.wordpress.org/browser/tags/4.8/src/wp-admin/edit-form-advanced.php#L135 ).

Here the sample code how to handle the messages.

Create new message (optional)

add_filter( 'post_updated_messages', function( $messages ) {
    //create another message code, i.e 11
    $messages['post'] = $messages['post'] + array( 11 => __( 'Something Wrong', 'textdomain' ) );

    return $messages;
} );

Handling redirection

add_filter( 'redirect_post_location', function( $location, $post_id ) {
    //let say the conditon is false, or you can create your code here
    $condition = false;

    if ( ! $condition ) //add 11 as code message or use in the list post messages
        $location = add_query_arg( 'message', 11, get_edit_post_link( $post_id, 'url' ) );


    return $location;
}, 10, 2 );

As those codex reference, code 0 will be give us no notice. The notice will always give update notice (green color), if we need error or warning notice, I suggest to create own admin notice. I hope this help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.