1

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?

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' );
  • Could you elaborate a bit? There are a lot of things that use POST method. :) – Rarst Oct 18 '13 at 19:46
  • I think the problem lies in that I run the code on a 'POST' Request Method and maybe the "Update File" button also has a post action associated with it. – whodeee Oct 18 '13 at 20:28
  • tried to post my own answer, but can't as I don't have a high enough rep... – whodeee Oct 18 '13 at 21:08
0

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.

  • Thanks @brasofilo I will check out those other link that you suggested. Not quite sure what you mean with your Ajax link, care to elaborate? – whodeee Oct 18 '13 at 21:37
  • To process the form without page refresh. Click submit, spinning wheel, Ajax does its thing, success message, presto. – brasofilo Oct 18 '13 at 22:04
  • Thanks for the suggestions @brasofilo - I added the nonce stuff and added prefixes to the fields. Still don't quite understand nonce but at least it seems to work. – whodeee Oct 21 '13 at 15:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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