• Resolved abufoysal

    (@abufoysal)


    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.

    • This topic was modified 4 years, 11 months ago by bcworkz. Reason: code fixed
Viewing 15 replies - 1 through 15 (of 20 total)
  • Moderator bcworkz

    (@bcworkz)

    You altered /wp-admin/admin-post.php? No! Please do not do that. Never alter core code files. By doing so, sooner or later your site will break. Leave that file alone.

    Hook the “admin_post_{$action}” action and output whatever you need. No other visible admin content is output and no actions that fire during the usual admin output like “admin_notices” fire unless your callback calls do_action() to cause them to fire.

    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz . I am absolutely new in WordPress Development. Could you please help me to do all those things you mentioned ? Sample code is helpful. Thanks.

    Moderator bcworkz

    (@bcworkz)

    Your request must include an “action” parameter along with any other data you require. It may be either POSTed or GET’d. example.info/wp-admin/admin-post.php?action=my_action
    The passed action value is used to compose the action hook tag.

    add_action('admin_post_my_action', 'my_callback_fn');
    function my_callback_fn() {
      // we are responsible for all page content
      echo '<!DOCTYPE html><html><head></head><body>'; // etc.
    
      // You could simply directly output your own notice here
      my_acf_notice();
      // but to utilize your notice callback for "admin_notices":
      do_action('admin_notices');
    
      // close open tags
      echo '</body></html>';
      exit();
    }
    • This reply was modified 4 years, 11 months ago by bcworkz. Reason: added exit() call
    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz for your reply. But in which file should I place these codes ?

    Moderator bcworkz

    (@bcworkz)

    Any plugin file that is parsed when plugins are loaded. The main file or anything included or required from that file.

    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz for your reply. I put your code in index.php file like below

    https://i.stack.imgur.com/U4STr.png

    My Form code is like below

    View post on imgur.com

    I am getting white page like below after submitting the Form.

    Dueling Network Screenshot

    Thanks

    Foysal

    Moderator bcworkz

    (@bcworkz)

    Which plugin file has the required plugin header? Similar to:

    <?php
    /**
     * Plugin Name: YOUR PLUGIN NAME
     */

    That file is where the action hook and callback should be. That file’s name (and its folder name) is recommended to be the plugin’s name. CRUD.php perhaps?

    You should define WP_DEBUG as true in wp-config.php when developing code so you can immediately see error notices and warnings instead of a blank white screen (often called the “White Screen of Death” or WSoD, an allusion to the infamous Windows crash blue screen of death)

    Please post code snippets in textual form instead of as screen grab images so we can better test or correct your code. Small snippets can be posted directly in these replies provided you demarcate with backticks or use the code button. You can also use resources like pastebin.com and gist.github.com and provide the resulting links here.

    Thread Starter abufoysal

    (@abufoysal)

    In my file structure index.php has the required plugin header. I placed below code in index.php file.

    add_action('admin_post_my_action', 'my_callback_fn');
    
    function my_callback_fn() {
        wp_die('hello');
    }

    Form is submitted to this link https://127.0.0.1/wordpressplugin/wp-admin/admin-post.php?action=my_action and I am getting blank white page. But if I refresh the URL then I am getting hello output.

    I defined WP_DEBUG as true in wp-config.php but I am not getting any error in either Web Page or in debug.log file.

    I posted screenshot for your convenience, so that you can get an idea about file structure.

    • This reply was modified 4 years, 10 months ago by abufoysal.
    Moderator bcworkz

    (@bcworkz)

    I agree seeing the file structure was somewhat useful, thank you. The code as image I could not test for myself, not so much ??

    I think wp_die() is sending inappropriate headers causing the behavior you see. Try replacing wp-die() call with:

    echo 'Hello world!';
    exit;
    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz for your solution.

    The code as image I could not test for myself, not so much

    You can help me with some self written Sample Code.

    I tried with your new Solution but result is as like before.

    I am simply trying to Submit a Form in Admin Panel. Here is the form https://i.stack.imgur.com/dIJEE.png

    Thanks

    Moderator bcworkz

    (@bcworkz)

    I wouldn’t normally write code upon request (beyond brief example snippets), but as it happens I just wrote a very similar admin form handler to do a data format conversion. The form is launched through a add_submenu_page() callback like you have. The submittal response makes no attempt at utilizing WP admin or theme styling. It’s a utility function for my own use, not for end users. I wouldn’t have even bothered with WP at all if my conversion didn’t need WP resources. I deleted all the use-specific code, leaving a generic outline of the process.

    https://pastebin.com/q40j4XvR

    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz for your reply.

    I applied your solution like below

    add_action('admin_post_my_action', 'my_callback_fn');
    
    	function my_callback_fn() {
    		?>
    			<!DOCTYPE html>
    			<html xmlns="https://www.w3.org/1999/xhtml" dir="ltr" lang="en-US">
    				<head>
    					<meta charset="utf-8" />
    					<meta name="viewport" content="width=device-width, initial-scale=1">
    					<title>Conversion Result</title>
    				</head>
    				<body>
    					<h1>Conversion Results</h1>
    					<?php
    						echo 'Hello world!';
    					?>
    				</body>
    			</html>
    		<?php
        exit;
    	}
    ?>

    But the result is as like before.

    Thanks

    Moderator bcworkz

    (@bcworkz)

    Well, it works for me. It’s hard to solve an issue if I cannot replicate it. Is the code you posted at the end of your plugin file? You shouldn’t have a closing ?> at the end of plugin files. Any extra white space afterwards will cause activation issues. It doesn’t cause problems when added to an active plugin, only on activation. So that alone would not cause the behavior you observe.

    You at one time had altered admin-post.php. Are you sure the file was properly restored? Maybe you should replace it with a clean version from a WP download. Be sure you use the same download version as your WP version.

    Thread Starter abufoysal

    (@abufoysal)

    Thanks @bcworkz for your reply. I installed a Fresh copy of WordPress 5.2.2 and tried again and got same output as before.

    My file structure is like below

    https://i.stack.imgur.com/th0G6.png

    My index.php file is like below

    https://pastebin.com/5n1Ph8Ly

    My newAddress.php file is like below

    https://pastebin.com/jDuHiuSs

    Why no one but you is replying in this Post ?

    Moderator bcworkz

    (@bcworkz)

    Still the same symptom, white screen, then on refresh it works normally? Very strange. Lets isolate the form handler code in its own separate plugin. Paste everything from line 50 down of your index.php into a new file in /plugins/ (sub-folder optional). Insert a new Plugin Name: comment header using a unique name. The action and function names now conflict with CRUD, eliminate the conflict by deactivating CRUD before activating this new mini-plugin.

    Request https://127.0.0.1/wordpressplugin/wp-admin/admin-post.php?action=my_action in your browser. You should get the expected output straight off. If so, we’re looking at the wrong code as the source of the problem. If not, maybe it’s a server configuration issue. Try opening your browser’s network developer tool before making the above request and see if anything unusual comes up, such as an unexpected redirect.

    The views of any topic tend to drop off the longer the thread gets. That doesn’t mean no one is following along. People will not reply in a topic if they cannot contribute towards a solution. This one is particularly mystifying.

Viewing 15 replies - 1 through 15 (of 20 total)
  • The topic ‘Use admin_notices Action hook’ is closed to new replies.