CSV Download from WordPress
January 28, 2025 ยท AI Conversations
User
Assistant
The provided code retrieves posts from the WordPress database and generates a CSV report for download. However, you mentioned not wanting to include the `$dataA[]` array and instead directly generate the CSV. Here's a modified version of your code that avoids using `$dataA[]` and directly writes to the CSV:
<?php
/* Template Name: Download Data */
global $wpdb;
$sqlcon = '';
$sqlj = '';
$pageNum = isset($_GET['pagen']) ? $_GET['pagen'] : 1;
$previousRows = ($pageNum - 1) * 500;
$totalRecord = "";
if (!empty($_GET['catex'])) {
if ($_GET['catex'] != -1) {
$sqlcon = "
AND tt.taxonomy = 'category'
AND t.term_id = '" . intval($_GET['catex']) . "'";
} else {
$sqlcon = "
AND tt.taxonomy = 'category'
AND t.term_id != '65'";
$totalRecord = "";
}
$sqlj = "
JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id)
JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
JOIN $wpdb->terms t ON (tt.term_id = t.term_id)";
}
$querystr = "SELECT
ID, post_title AS title, post_modified
FROM $wpdb->posts p
$sqlj
WHERE p.post_type = 'post' AND p.post_status = 'publish'
$sqlcon
ORDER BY post_date DESC
$totalRecord";
$pageposts = $wpdb->get_results($querystr, OBJECT);
// Prepare the output for CSV
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="post_report_data.csv";');
$output = fopen('php://output', 'w');
// Add CSV header
fputcsv($output, ['Title', 'Url', 'Feature Image Url', 'Category', 'Revision Date', 'Meta Description']);
// Fetch and write each post's data directly
foreach ($pageposts as $post) {
$url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'thumbnail');
$categories = implode(', ', array_map(function ($cat) {
return $cat->cat_name;
}, get_the_category($post->ID)));
fputcsv($output, [
$post->title,
get_permalink($post->ID),
$url,
$categories,
get_the_modified_date('Y-m-d H:i:s', $post->ID),
get_post_meta($post->ID, '_yoast_wpseo_metadesc', true)
]);
}
fclose($output);
exit;
### Key Changes:
1. **Direct Output to CSV**: Replaced the `$dataA[]` array with direct calls to `fputcsv` on the output stream.
2. **Security Improvements**:
– Sanitized the `$_GET['catex']` input using `intval()` to prevent SQL injection.
– Used single quotes for SQL to avoid dynamic variable parsing.
3. **CSV Headers**: Added headers directly in the CSV output.
This code dynamically streams the CSV data without using a temporary array, which is more memory-efficient for large datasets.