0

I am trying to display some error messages in case some conditions are not met when using wp_insert_post. However, it the admin_notice doesn't seem to trigger.

Here's the example I have:

    add_action( 'wp_insert_post', 'automate_intercom', 10, 3);
    function automate_intercom($post_id, $post, $update) {

        if($post->post_status == 'publish' && $post->post_type == 'help-center') {
            
            $someCondition = '';

            if($someCondition!== '') {

            }else{
                add_action( 'admin_notices', 'show_example_error' );


            }


        }
    }

    function show_example_error() {
        $class = 'notice notice-info';
        $message = __( 'Example error', 'admin_notice' );
        error_log("In admin notice ");
    printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), $message); 
    }

Any ideas why it doesn't trigger the admin_notices?

1 Answer 1

0

Hooks cannot be added directly inside functions. Using do_action, you can invoke a custom hook.

In your case try out the below solution:

add_action( 'wp_insert_post', 'automate_intercom', 10, 3 );
function automate_intercom( $post_id, $post, $update ) {

    if ( $post->post_status == 'publish' && $post->post_type == 'help-center' ) {

        $someCondition = '';

        if ( $someCondition !== '' ) {

        } else {
            show_example_error();
        }
    }
}

function show_example_error() {
    $screen = get_current_screen();
    if ( $screen->post_type == 'help-center' ) {
        $class   = 'notice notice-info';
        $message = __( 'Example error', 'admin_notice' );
        error_log( 'In admin notice ' );
        printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), $message );
    }
}
add_action( 'admin_notices', 'show_example_error' );
9
  • which one should be do_action?
    – dvm node
    Jan 13, 2023 at 9:17
  • When you have a custom hook then you can use do_action but right now you can try out the above solution. Just call show_example_error() function when your conditions are not satisfied. Jan 13, 2023 at 9:30
  • oh it does work, but i just realized that the admin notice is hidden during post publish/updating. Is there any way I could make this display or should I look into another solution?
    – dvm node
    Jan 13, 2023 at 10:11
  • But you have given the condition that post_status->publish after that it will call function. So it will show after your post published Jan 13, 2023 at 10:15
  • shouldnt it show during the publishing/updating process? right now it only shows here: freeimage.host/i/HYcLYTG
    – dvm node
    Jan 13, 2023 at 10:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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