WordPress Plugin: Call function on button click in admin panel

前端 未结 2 1298
清歌不尽
清歌不尽 2021-01-31 09:30

I need to create a WordPress plugin that calls a PHP function when a button in an admin panel is clicked. I\'ve been looking at tutorials for writing basic WordPress plugins an

2条回答
  •  抹茶落季
    2021-01-31 10:16

    Although the answers on this page provided a useful start, it took a while for me to figure out how to get option (2) working. Given this, the following code might be of help to some people.

    If you create a plugin with the following code and it will add a left hand menu option called 'Test Button' when you are in the admin area. Click on this and you will see a button. Clicking that button runs the test_button_action function. In my example function I've both put a message on the page and written to a log file.

    ';
    
      echo '

    Test Button Demo

    '; // Check whether the button has been pressed AND also check the nonce if (isset($_POST['test_button']) && check_admin_referer('test_button_clicked')) { // the button has been pressed AND we've passed the security check test_button_action(); } echo '
    '; // this is a WordPress security feature - see: https://codex.wordpress.org/WordPress_Nonces wp_nonce_field('test_button_clicked'); echo ''; submit_button('Call Function'); echo '
    '; echo '
    '; } function test_button_action() { echo '

    ' .'The "Call Function" button was clicked.' . '

    '; $path = WP_TEMP_DIR . '/test-button-log.txt'; $handle = fopen($path,"w"); if ($handle == false) { echo '

    Could not write the log file to the temporary directory: ' . $path . '

    '; } else { echo '

    Log of button click written to: ' . $path . '

    '; fwrite ($handle , "Call Function button clicked on: " . date("D j M Y H:i:s", time())); fclose ($handle); } } ?>

提交回复
热议问题