问题
I've been coding in PHP for a long time, but I'm currently writing my first Wordpress plugin. The plugin's goals are:
- Display a form on a public-facing page to collect simple data from site visitors (first/last name, etc)
- Provide a way for admins export the data
I've got a plugin that successfully creates a table on activation and a shortcode that provides a form which successfully stores the submitted data in the database.
On the back-end, I have a dashboard widget that currently displays some stats about the submissions, and my last task is to provide a button to export those stats to CSV, and that's where I'm stumped. I'm not sure how to handle this in WP world...in the past, I would have had the button open a new window to a page that does the exporting and echos a CSV string to the page along with headers that indicate it's a binary file so it's downloaded. In WP, how do I accomplish this? Do I put a PHP script in my plugin directory and have my widget open that page? If so, how does that page gain access to $wpdb to handle the data access?
Here is my code (just for the dashboard widget part) as it stands now:
<?php
/*
Plugin meta details
*/
add_action('init', 'myplugin_buffer_start');
add_action('wp_footer', 'myplugin_buffer_end');
function myplugin_ob_callback($buffer) {
// You can modify buffer here, and then return the updated code
return $buffer;
}
/**
* Action: init
* Runs after WP has finished loading but before any headers are sent, user is already authenticated at this point
* Good for intercepting $_POST/$_GET
*/
function myplugin_buffer_start()
{
ob_start("myplugin_ob_callback");
}
/**
* Action wp_footer
* Triggered near the </body> tag of the user's template by the wp_footer() function.
*/
function myplugin_buffer_end()
{
ob_end_flush();
}
/****************************************************************
* Stats Dashboard Widgets
***************************************************************/
function myplugin_displaytestFormWidget_process()
{
$errors = array();
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
ob_end_clean(); // erase the output buffer and turn off buffering...blow away all the markup/content from the buffer up to this point
global $wpdb;
$tableName = $wpdb->prefix . "myplugin_test_form";
$qry = "select Name, Date from $tableName order by Date desc";
//ob_start(); when I uncomment this, it works!
$result = $wpdb->get_results($qry, ARRAY_A);
if ($wpdb->num_rows)
{
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "myCsvFile-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
//$headrow = $result[0];
//fputcsv($fp, array_keys($headrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
//when I uncomment these lines along with adding ob_start above, it works
//$contLength = ob_get_length();
//header( 'Content-Length: '.$contLength);
}
}
return myplugin_displaytestFormWidget();
}
function myplugin_displaytestFormWidget()
{
global $wpdb;
$tableName = $wpdb->prefix . "myplugin_test_form";
$submissionCount = $wpdb->get_var("select count(Id) from $tableName");
?>
<div><strong>Last entry: </strong>John Q. test (May 5, 2013)</div>
<div><strong>Total submissions: </strong> <?php echo $submissionCount ?></div>
<form id="myplugin_test_export_widget" method="post" action="">
<input type="submit" name="myplugin_export_button" value="Export All" />
</form>
<?php
}
function myplugin_addDashboardWidgets()
{
// widget_id, widget_name, callback, control_callback
wp_add_dashboard_widget(
'test-form-widget',
'test Form Submissions',
'myplugin_displaytestFormWidget_process'
);
}
/****************************************************************
* Hooks
***************************************************************/
//add_action('widgets_init', 'simple_widget_init');
add_action('wp_dashboard_setup', 'myplugin_addDashboardWidgets' );
// This shortcode will inject the form onto a page
add_shortcode('test-form', 'myplugin_displaytestForm_process');
register_activation_hook(__FILE__, 'myplugin_test_form_activate');
You can see in the myplugin_displayTestFormWidget function I'm displaying the form, I just don't know what to do with the button to make it all jive.

Can anyone assist?
回答1:
At first add following code in your plugin
add_action('init', 'buffer_start');
add_action('wp_footer', 'buffer_end');
function callback($buffer) {
// You can modify buffer here, and then return the updated code
return $buffer;
}
function buffer_start() { ob_start("callback"); }
function buffer_end() { ob_end_flush(); }
Just at the top, right after the plugin meta info like
/**
* @package Word Generator
* @version 1.0
* ...
*/
// here goes the code given above, it'll solve the header sent error problem
And following code will dump a csv file
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
// Somehow, perform the export
ob_clean();
global $wpdb;
$qry = 'your query';
$result = $wpdb->get_results($qry, ARRAY_A);
if ($wpdb->num_rows){
$date = new DateTime();
$ts = $date->format("Y-m-d-G-i-s");
$filename = "myCsvFile-$ts.csv";
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);
$fp = fopen('php://output', 'w');
$headrow = $result[0];
fputcsv($fp, array_keys($headrow));
foreach ($result as $data) {
fputcsv($fp, $data);
}
fclose($fp);
$contLength = ob_get_length();
header( 'Content-Length: '.$contLength);
exit();
}
}
回答2:
I've implemented similar functionality in another plugin I developed a while ago. I won't claim it's the best practice (I'm not 100% sure if there is such a thing in this instance) but it seemed like a clean and reliable solution for me at the time.
Picking up from where you left off, inside your myplugin_displayTestFormWidget_process
function, let me just put some real and pseudo code that should get you rolling.
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && isset ( $_POST['myplugin_export_button'] ))
{
// clear out the buffer
ob_clean();
// get the $wpdb variable into scope so you may use it
global $wpdb;
// define some filename using a timestamp maybe
// $csv_file_name = 'export_' . date('Ymd') . '.csv';
// get the results of your query
$result = $wpdb->get_results("SELECT * FROM your_table");
// loop your results and build your csv file
foreach($result as $row){
// put your csv data into something like $csv_string or whatever
}
header("Content-type: text/x-csv");
header("Content-Transfer-Encoding: binary");
header("Content-Disposition: attachment; filename=".$csv_file_name);
header("Pragma: no-cache");
header("Expires: 0");
echo $csv_string;
exit;
}
You mentioned you are pretty comfortable with PHP so I didn't really dig into the PHP aspects of getting this done.
Hope that helps, have fun!
来源:https://stackoverflow.com/questions/16722818/wordpress-admin-widget-that-exports-data