0

我已经用 PHP 编码很长时间了,但我目前正在编写我的第一个 Wordpress 插件。该插件的目标是:

  • 在面向公众的页面上显示一个表单,以从网站访问者那里收集简单的数据(名字/姓氏等)
  • 为管理员提供一种导出数据的方式

我有一个插件,它成功地创建了一个激活表和一个短代码,它提供了一个成功地将提交的数据存储在数据库中的表单。

在后端,我有一个仪表板小部件,当前显示有关提交的一些统计信息,我的最后一项任务是提供一个按钮以将这些统计信息导出到 CSV,这就是我难过的地方。我不确定如何在 WP 世界中处理这个问题......过去,我会让按钮打开一个新窗口到一个页面,该页面执行导出并将 CSV 字符串与指示它的标题一起回显到页面一个二进制文件,所以它被下载了。在 WP 中,我该如何做到这一点?我是否将 PHP 脚本放在我的插件目录中并让我的小部件打开该页面?如果是这样,该页面如何访问 $wpdb 来处理数据访问?

这是我现在的代码(仅用于仪表板小部件部分):

<?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');

您可以在myplugin_displayTestFormWidget函数中看到我正在显示表单,我只是不知道如何处理按钮以使其全部运行。

小部件输出的屏幕截图

有人可以帮忙吗?

4

2 回答 2

2

首先在您的插件中添加以下代码

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(); }

就在顶部,就在插件元信息之后

/**
 * @package Word Generator
 * @version 1.0
 * ...
 */
 // here goes the code given above, it'll solve the header sent error problem

以下代码将转储一个 csv 文件

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();
    }
}
于 2013-05-23T22:30:41.620 回答
0

我在不久前开发的另一个插件中实现了类似的功能。我不会声称这是最佳实践(我不能 100% 确定在这种情况下是否存在这样的事情),但它在当时对我来说似乎是一个干净可靠的解决方案。

从你离开的地方开始,在你的myplugin_displayTestFormWidget_process函数中,让我放一些应该让你滚动的真实和伪代码。

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;
}

您提到您对 PHP 非常熟悉,所以我并没有真正深入研究完成这项工作的 PHP 方面。

希望有帮助,玩得开心!

于 2013-05-23T20:40:44.103 回答