插件设置页面中的下载按钮

时间:2019-07-10 作者:GuitarExtended

我正在编写一个简单的插件,为此我创建了一个通过菜单访问的简单设置页面。在这个设置页面中,除其他外,我希望有一个按钮来下载由PHP脚本中的函数创建的文件。

add_action(\'admin_menu\', \'my_plugin_menu\');

function my_plugin_menu() {
    add_menu_page(\'Plugin management\', \'Plugin management\', \'manage_options\', \'my_plugin-plugin-settings\', \'my_plugin_settings_page\', \'dashicons-admin-generic\');
}


function my_plugin_settings_page() {
    if ( !current_user_can( \'manage_options\' ) )  {
        wp_die( __( \'You do not have sufficient permissions to access this page.\' ) );
    }
    ?>
        <p>Please click the button below to download the file.</p>
        <button id="export-file">Download the file</button>

    </div>
    <?php
}

function trigger_download() {
// This function should build the file (for instance a simple .txt) and trigger the download dialog in the user\'s browser.
    }
我不知道下一步要做什么。我发现我必须设置特定的标题,例如:

header( "Content-Description: File Transfer" );
header( "Content-Disposition: attachment; filename={$file_name}" );
header( "Content-Type: application/json; charset=utf-8" );
但是我不知道当点击按钮时应该调用什么样的操作(一般来说,我对表单和GET-POST方法不太了解,但我很高兴了解)。

1 个回复
最合适的回答,由SO网友:GuitarExtended 整理而成

我通过以下代码获得了我想要的行为:

add_action(\'admin_menu\', \'my_plugin_menu\');

function my_plugin_menu() {
    add_menu_page(\'Plugin management\', \'Plugin management\', \'manage_options\', \'my_plugin-plugin-settings\', \'my_plugin_settings_page\', \'dashicons-admin-generic\');
}


function my_plugin_settings_page() {
    if ( !current_user_can( \'manage_options\' ) )  {
        wp_die( __( \'You do not have sufficient permissions to access this page.\' ) );
    }
    ?>
        <p>Please click the button below to download the file.</p>
        <form action="http://my-website-url/wp-admin/admin-post.php?action=add_foobar&data=foobarid" method="post">
          <input type="hidden" name="action" value="add_foobar">
          <input type="hidden" name="data" value="foobarid">
          <input type="submit" value="Download the file">
        </form>

    </div>
    <?php
}

// From : https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action)
add_action( \'admin_post_add_foobar\', \'prefix_admin_add_foobar\' );

function prefix_admin_add_foobar() {
    // Handle request then generate response using echo or leaving PHP and using HTML
    $filename = "file.csv";
    $array = array(array(1,2,3,4), array("merle","mésange","pie","coucou"));
    $delimiter = ",";

    header(\'Content-Type: application/csv\');
    header(\'Content-Disposition: attachment; filename="\'.$filename.\'";\');

    // open the "output" stream
    // see http://www.php.net/manual/en/wrappers.php.php#refsect2-wrappers.php-unknown-unknown-unknown-descriptioq
    $f = fopen(\'php://output\', \'w\');

    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
    die();
}
Theadmin_post_(action) 胡克很有帮助。

相关推荐