3

Trying to export to CSV from WordPress front end. Here is what I have so far. I was able to export to CSV from the admin area, but for some reason I am unable to export from the front end. What am I doing wrong here?

// Add action hook only if action=download_csv_sl
if ( isset($_GET['action'] ) && $_GET['action'] == 'download_csv_sl' )  {
// Handle CSV Export
add_action( 'init', 'csv_export_sl');
}

function csv_export_sl() {
    // Check if we are in WP-Admin
    if( is_admin() ){ return false; }

    // Nonce Check
    $nonce = isset( $_GET['_wpnonce'] ) ? $_GET['_wpnonce'] : '';
    if ( ! wp_verify_nonce( $nonce, 'download_csv_sl' ) ) {
        die( 'Security check error' );
    }

    // Get Current Date and Time
    date_default_timezone_set('America/Denver');
    $currentDate = date('Y_m_d-H_i_s');

    $domain = $_SERVER['SERVER_NAME'];
    $filename = 'Store_List-' . $currentDate . '.csv';

    // Get Quarter and Ranking from Shop Profiles
    $getQuarter = do_shortcode('[usermeta key="current_quarter" user="717"]');
    if ($getQuarter == '1'){
        $currentQuarter = 'ranker_q1';
    } elseif ($getQuarter == '2'){
        $currentQuarter = 'ranker_q1_89';
    } elseif ($getQuarter == '3'){
        $currentQuarter = 'ranker_q1_90';
    } elseif ($getQuarter == '4'){
        $currentQuarter = 'ranker_q1_91';
    } else {
        $currentQuarter = '';
    }

    // Name the columns in the spreadsheet
    $header_row = array(
        'Store Number',
        'Address',
        'Franchisee',
        'Q'.$getQuarter.' Ranking'
    );
    $data_rows = array();

    // Query users
    $user_query = new WP_User_Query( array(
        'role__in'    => ['shop','shop_co','shop_noco'],
        'orderby' => 'meta_value_num',
        'order' => 'ASC',
    ) );   
    $users = $user_query->get_results();

    foreach ( $users as $user ) {
        if (!empty($user->Group)){
            $row = array(
                $user->Store_Number,             // Get Store Number
                $user->Address,                  // Get Address
                $user->display_name,             // Get Franchisee
                $user->$currentQuarter          // Get Ranking
            );
            $data_rows[] = $row;
        }
    }

    $fh = @fopen( 'php://output', 'w' );
    fprintf( $fh, chr(0xEF) . chr(0xBB) . chr(0xBF) );
    header( 'Cache-Control: must-revalidate, post-check=0, pre-check=0' );
    header( 'Content-Description: File Transfer' );
    header( 'Content-Transfer-Encoding: UTF-8' );
    header( 'Content-type: text/csv' );
    header( "Content-Disposition: attachment; filename={$filename}" );
    header( 'Expires: 0' );
    header( 'Pragma: public' );
    fputcsv( $fh, $header_row );
    foreach ( $data_rows as $data_row ) {
        fputcsv( $fh, $data_row );
    }
    fclose( $fh );

    ob_end_flush();

    die();
}

add_shortcode('bc_export', 'csv_export_storelist_shortcode');
function csv_export_storelist_shortcode() {
    $url = $_GET['uri'];
    $nonce = wp_create_nonce( 'download_csv_sl' );
    $exportList = '<a href="'. $url . '&action=download_csv_sl&_wpnonce='. $nonce .'" class="page-title-action">Export to CSV</a>';
    return $exportList;
}

It seems the issue lies in the $url link path inside the shortcode, but I can't figure out what the path is. The current code results in a Page Not Found when clicking on the link.

0

Nevermind, I figured out a way to make it work. I just removed the need for a url altogether. Here's what I did in case anybody else wants to know.

I changed the link to an form input button:

<form method="post">
    <input type="submit" name="bc_export" class="btn btn-export" value="Export Store List for '.$atts['value'].'" />
</form>

And changed the $_GET['action'] to a $_POST[]:

if ( isset($_POST["bc_export"])) {
    add_action( 'init', 'bc_export_function');
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.