skip to Main Content

For my CPT I use some extra meta data.
I want verify the meta data and if there is something wrong show an error.

With some research I try this code

add_action('save_post', function($post_id){
    if(isset($_POST['joLink'])){
        if($_POST['joLink'] !== ''){
            update_post_meta($post_id, 'joLink', $_POST['joLink']);
        }else{
            add_settings_error(
                'missing-link',         
                'missing-link',         
                'Link may not empty!',          
                'error' 
            );
            add_action('admin_notices', function(){
                $message = '<div id="message" class="error"><p><ul>';         
                foreach ( $errors as $error ) {         
                    $message .= '<li>' . $error['message'] . '</li>';         
                }         
                $message .= '</ul></p></div>';      
                echo $message;
            });
        }
    }else{
        delete_post_meta($post_id, 'joLink');
    }
    
    return $post_id;
});

If I save the post with a empty link WordPress saved the data and returns success.
What I am missing?

2

Answers


  1. One way to cancel the post save is just die.

    
    add_action('save_post', function ($post_id) {
        if (true) {
            wp_die(__('Link may not empty!', 'your-text-domain'));
        }
        return $post_id;
    });
    
    
    Login or Signup to reply.
  2. The Gutenberg block editor use Javascript to display messages

     wp.data.dispatch( 'core/notices' ).createNotice(
            'error',
            'Hey, something going wrong!',
            { 
                id:'greetings-notice', 
                isDismissible: true,
            }
        );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search