Plugin de WordPress: Función de llamada en el botón haga clic en el panel de administración


Necesito crear un plugin de WordPress que llame a una función PHP cuando se haga clic en un botón en un panel de administración. He estado mirando tutoriales para escribir plugins básicos de WordPress y agregar paneles de administración, pero todavía no entiendo cómo registrar exactamente un botón para una función específica en mi plug-in.

Esto es lo que tengo hasta ahora:

/*
Plugin Name: 
Plugin URI: 
Description: 
Author:
Version: 1.0
Author URI:
*/


add_action('admin_menu', 'wc_plugin_menu');

function wc_plugin_menu(){
 add_management_page('Title', 'MenuTitle', 'manage_options', 'wc-admin-menu', 'wc_plugin_options'); 

}

function wc_plugin_options(){
if (!current_user_can('manage_options'))  {
    wp_die( __('You do not have sufficient permissions to access this page.')    );
}
echo '<div class="wrap">';
echo '<button>Call Function!</button>'; //add some type of hook to call function
echo '</div>';

}

function button_function()
{
//do some stuff
} 


?>
 24
Author: Maxime, 2011-12-22

2 answers

Bueno, tienes dos opciones.

1) Use AJAX para crear un gancho admin-ajax que ejecute con JavaScript cuando el usuario haga clic en el botón. Puedes aprender sobre este enfoque aquí: http://codex.wordpress.org/AJAX (asegúrese de agregar un nonce para la seguridad ( http://codex.wordpress.org/WordPress_Nonces )). Este también es un buen recurso para crear ganchos admin-ajax: http://codex.wordpress.org/AJAX_in_Plugins

2) Poner el botón en un formulario, PUBLICAR que formulario a su plugin y añadir algún código para manejar el formulario POST'd (si lo hace, asegúrese de incluir un nonce para la seguridad ( http://codex.wordpress.org/WordPress_Nonces) y también asegúrese de que el usuario que intenta hacer clic en el botón tiene los privilegios adecuados para hacerlo http://codex.wordpress.org/Function_Reference/current_user_can

Lo que está tratando de hacer no es súper complejo, pero implica una buena comprensión de los formularios, PHP y (tal vez) JavaScript. Si su JavaScript está bien, recomendaría la opción 1, ya que no requiere que el usuario vuelva a cargar la página.

 24
Author: brandwaffle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-22 01:28:09

Aunque las respuestas en esta página proporcionaron un comienzo útil, me llevó un tiempo descubrir cómo hacer que la opción (2) funcionara. Dado esto, el siguiente código podría ser de ayuda para algunas personas.

Si crea un plugin con el siguiente código y añadirá una opción de menú de la izquierda llamada 'Botón de prueba' cuando esté en el área de administración. Haga clic en esto y verá un botón. Al hacer clic en ese botón se ejecuta la función test_button_action. En mi función de ejemplo he puesto un mensaje en la página y escrito en un archivo de registro.

<?php

/*
Plugin Name: Example of Button on Admin Page
Plugin URI: 
Description: 
Author:
Version: 1.0
Author URI:
*/


add_action('admin_menu', 'test_button_menu');

function test_button_menu(){
  add_menu_page('Test Button Page', 'Test Button', 'manage_options', 'test-button-slug', 'test_button_admin_page');

}

function test_button_admin_page() {

  // This function creates the output for the admin page.
  // It also checks the value of the $_POST variable to see whether
  // there has been a form submission. 

  // The check_admin_referer is a WordPress function that does some security
  // checking and is recommended good practice.

  // General check for user permissions.
  if (!current_user_can('manage_options'))  {
    wp_die( __('You do not have sufficient pilchards to access this page.')    );
  }

  // Start building the page

  echo '<div class="wrap">';

  echo '<h2>Test Button Demo</h2>';

  // 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 '<form action="options-general.php?page=test-button-slug" method="post">';

  // this is a WordPress security feature - see: https://codex.wordpress.org/WordPress_Nonces
  wp_nonce_field('test_button_clicked');
  echo '<input type="hidden" value="true" name="test_button" />';
  submit_button('Call Function');
  echo '</form>';

  echo '</div>';

}

function test_button_action()
{
  echo '<div id="message" class="updated fade"><p>'
    .'The "Call Function" button was clicked.' . '</p></div>';

  $path = WP_TEMP_DIR . '/test-button-log.txt';

  $handle = fopen($path,"w");

  if ($handle == false) {
    echo '<p>Could not write the log file to the temporary directory: ' . $path . '</p>';
  }
  else {
    echo '<p>Log of button click written to: ' . $path . '</p>';

    fwrite ($handle , "Call Function button clicked on: " . date("D j M Y H:i:s", time())); 
    fclose ($handle);
  }
}  
?>
 18
Author: Obliquely,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-27 13:02:14