Dashboard Widget Form

I created a Dashboard widget to send push notifications to an app, but the way I have it coded, whenever I make changes in the Plugin Editor and press Update File, the code gets ran and I get a blank push notification.
I am sure my problem lies in this part of the plugin code:

if('POST' == $_SERVER['REQUEST_METHOD']) {
    // process the form here
}

Any suggestions on how to fix this or a better way to do it?

Read More

Here is the gist of my plugin code

if('POST' == $_SERVER['REQUEST_METHOD']) {
  //do the stuff with the 'message'
}


// Function that outputs the contents of the dashboard widget
function dashboard_widget_function() {
    echo '<form method="post">
    <p>Message: <input type="text" name="message" /></p>
    <p><input type="submit" /></p>
    </form>';
}

// Function used in the action hook
function add_dashboard_widgets() {
    wp_add_dashboard_widget('push_notification', 'Push Notification', 'dashboard_widget_function');
}

// Register the new dashboard widget with the 'wp_dashboard_setup' action
add_action('wp_dashboard_setup', 'add_dashboard_widgets' );

Related posts

1 comment

  1. That if('POST'...) just alone -in the middle of the plugin code- doesn’t seem right. You can hook into load-$pagenow and process the form submission there:

    add_action( 'load-index.php', 'check_posted_data' );
    function check_posted_data()
    {
        if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['my_prefix_message'] ) ) {
            wp_die( "I'm here! {$_POST['my_prefix_message']}" );
        }
    }
    

    Please note that you’re missing security checks and proper prefixes to your data.

    And as a side note, I would solve this with Ajax.

Comments are closed.