导出数据的 Wordpress 管理小部件 [英] Wordpress admin widget that exports data

查看:32
本文介绍了导出数据的 Wordpress 管理小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been coding in PHP for a long time, but I'm currently writing my first Wordpress plugin. The plugin's goals are:

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

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

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.

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

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

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

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.

有人可以帮忙吗?

推荐答案

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

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

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

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

这篇关于导出数据的 Wordpress 管理小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆