Use admin_notices Action hook

Question

I am learning plugin development. I am submitting a Form in admin-post.php from Admin Panel. I would like to show a Admin Notice while a Form field is empty. My admin-post.php file is like below.

<?php

if ( ! defined( 'WP_ADMIN' ) ) {
    define( 'WP_ADMIN', true );
}

if ( defined( 'ABSPATH' ) ) {
    require_once( ABSPATH . 'wp-load.php' );
} else {
    require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
}
send_origin_headers();

require_once( ABSPATH . 'wp-admin/includes/admin.php' );

nocache_headers();
do_action( 'admin_init' );

$action = empty( $_REQUEST['action'] ) ? '' : $_REQUEST['action'];

if ( ! is_user_logged_in() ) {
    if ( empty( $action ) ) {

        do_action( 'admin_post_nopriv' );
    } else {

        do_action( "admin_post_nopriv_{$action}" );
    }
} else {

        add_action( 'admin_post_addAddress', 'add_new_address' );

        function my_acf_notice() {
            ?>
            <div class="update-nag notice">
                    <p><?php _e( 'Name field is empty!', 'my_plugin_textdomain' ); ?></p>
            </div>
            <?php
        }

        function add_new_address(){
        if($_POST['name'] == '') {
            add_action( 'admin_notices', 'my_acf_notice' );  // This line is not working.           
        }

        $retrieved_nonce = $_REQUEST['_wpnonce'];
        if (wp_verify_nonce($retrieved_nonce, 'add_new_address' ) ) {
            if(isset( $_POST['add_new_address'] )) {
                global $wpdb;
                $sql = $wpdb->prepare(
                "INSERT INTO `".$wpdb->prefix."afaddresss`(`name`,`email`,`phone_no`,`address`,`photo`) values ( %s, %s, %s,%s, %s ) ", array($_POST['name'], $_POST['email'], $_POST['phone_no'], $_POST['address'], $_POST['photo']));
                $result = $wpdb->query($sql);
                if($result) {
                    wp_redirect( admin_url( '/admin.php?page=addressPage' ) );
                }
            }
        }
    }

    if ( empty( $action ) ) {
        do_action( 'admin_post' );
    } else {
        do_action( "admin_post_{$action}" );
    }
}

But this line add_action( 'admin_notices', 'my_acf_notice' ); is not working.

0
, Foysal 2 years 2019-11-22T09:11:36-05:00 0 Answers 70 views 0

Leave an answer

Browse
Browse