admin管理员组

文章数量:1122846

Who can help me a little.

I try to get an admin error notice if a metabox field is empty during save post. Wordpress refresh the page after saving so the hook admin_notices does not work.

Here is my saving code

add_action('save_post', function($post_id){
    if(isset($_POST['add']) && $_POST['add'] != ''){
        update_post_meta($post_id, 'add', $_POST['add']);
    }else{
        add_action( 'admin_notices', function(){
        ?>
            <p><?php _e( 'Error!', 'Field add is empty!' ); ?></p>
        <?php
        });
    }
}

Who can help me a little.

I try to get an admin error notice if a metabox field is empty during save post. Wordpress refresh the page after saving so the hook admin_notices does not work.

Here is my saving code

add_action('save_post', function($post_id){
    if(isset($_POST['add']) && $_POST['add'] != ''){
        update_post_meta($post_id, 'add', $_POST['add']);
    }else{
        add_action( 'admin_notices', function(){
        ?>
            <p><?php _e( 'Error!', 'Field add is empty!' ); ?></p>
        <?php
        });
    }
}
Share Improve this question asked May 20, 2024 at 22:32 RickBRickB 1 1
  • Would it not make more sense to add the required attribute to the meta field? – Chris Cox Commented May 26, 2024 at 11:18
Add a comment  | 

1 Answer 1

Reset to default 0

You could for example save an error flag to a transient in save_post, if a required field is empty, and the display the admin notice based on the transient. This concept is demonstrated in in this old answer.

Another option is to add a simple script to the editing view which would alert the user that the said field is empty. Or just add required html attribute to the input field.

本文标签: hooksShow admin notice if metabox field is empty during save post