php - Export Wordpress User Meta to CSVExcel

admin2025-04-20  0

I have shops and consultants both set up on Wordpress as users with different roles. I want to include an "Export" link on the consultants' profiles using a shortcode that will export the shops on their list to evaluate to a CSV/Excel file. The consultants' display names have been added to the shop profiles as meta data, so I'm trying to call all of the shops that include their name. This is what I have so far, and I can't seem to figure it out from here.

  • The shortcode attribute 'bc' grabs the consultant's display name
  • $shop_query looks for all shops that match the consultant's display name
  • $lineData includes the meta-keys of the shop information that I want to include in the CSV file

Any help would be greatly appreciated. :)

function fc_pbestorelist_export_functions($atts) {
$atts = shortcode_atts( array(
    'bc' => do_shortcode('[display_name]'),
), $atts );         
if(isset($_GET['export'])){
    if($_GET['export'] == 'true'){
       $shop_query = new WP_User_Query( array( 
          'meta_key' => 'Group',
          'meta_value' => $atts['bc'],
          'role__in'    => wp_parse_list( ['shop','shop_co','shop_noco'] ),
       ) );    
       $query = $shop_query->get_results();

       $delimiter = ',';
       $filename = 'ShopList_' . date('Ymd') . '.csv'; // Create file name

       //create a file pointer
       $f = fopen('ShopList', 'r'); 

       //set column headers
       $fields = array('Username', 'Email', 'pbe_evaltype_month1', 'pbe_evaltype_month2', 'pbe_evaltype_month3');
       fputcsv($f, $fields, $delimiter);

       //output each row of the data, format line as csv and write to file pointer
       while($row = $query->fetch_assoc()){
          $lineData = array($row['nicename'], $row['user_email'], $row['pbe_evaltype_month1'], $row['pbe_evaltype_month2'], $row['pbe_evaltype_month3']);
          fputcsv($f, $lineData, $delimiter);
       }

       //move back to beginning of file
       fseek($f, 0);

       //set headers to download file rather than displayed
       header('Content-Type: text/csv');
       header('Content-Disposition: attachment; filename="' . $filename . '";');

       //output all remaining data on a file pointer
       fpassthru($f);
       }
    }
    $results = '<a href=/user/?export=true>Export CSV</a>';
}
wp_reset_postdata();
return $results;
}
add_shortcode( 'fc_pbestorelist_export', 'fc_pbestorelist_export_functions' );
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745114197a285764.html

最新回复(0)