Snippets

Pavel Petrov How to serve file downloads from WordPress plugin

Created by Pavel Petrov
<?php
//functions.php
add_action('init', function(){
    if ((bool) $_GET['export'] == true && ($_GET['type'] == 'dummydata1' || $_GET['type'] == 'dummydata2') && is_admin()) {
            header('Content-Type: text/csv; charset=utf-8');
            header('Content-Disposition: attachment; filename='.uniqid().'.csv');
            header('Pragma: no-cache');
            header('Expires: 0');
 
            $output = fopen('php://output', 'w');
            fputcsv($output, ['URL', 'Hits']);
            
            if ($_GET['type'] == 'dummydata1') {
                    //...
                    //Some business logic here
                    return ['test.net' => (object)['hits' => 131];
                };
            }
            if ($_GET['type'] == 'dummydata2') {
                    //...
                    //Some business logic here
                    return ['test1.net' => (object)['hits' => 142];
                };
            }
 
            foreach ($transformSubmissions() as $url => $goal) {
                fputcsv($output, [$this->punnycoder->decode($url), $goal->hits]);
            }
            exit;
        }
}, 1);

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.