Skip to content

Instantly share code, notes, and snippets.

@edpittol
Created December 13, 2023 14:26
Show Gist options
  • Save edpittol/235cdab20b679e43a7547f46de9082bc to your computer and use it in GitHub Desktop.
Save edpittol/235cdab20b679e43a7547f46de9082bc to your computer and use it in GitHub Desktop.
Script extracts WordPress table data via WP-CLI, handles provided table name as argument, queries database, outputs CSV format through eval-file command in WP-CLI
<?php
/**
* Export WordPress table data using WP-CLI eval-file command.
* Usage: wp eval-file export-table.php your_table_name_here
*/
if (!defined('WP_CLI') || !WP_CLI) {
echo "This script is intended to be used with WP-CLI.\n";
return;
}
// Get the global WordPress database class
global $wpdb;
// Check if a table name is provided as an argument
$args = WP_CLI::get_runner()->arguments;
$table_name = isset($args[2]) ? $args[2] : '';
if (empty($table_name)) {
WP_CLI::error('Please provide a table name as an argument.');
return;
}
// Query to select data from the table
$query = "SELECT * FROM $table_name";
// Get the results from the database
$results = $wpdb->get_results($query, ARRAY_A);
// Output the data to stdout (in CSV format)
if (empty($results)) {
WP_CLI::warning("No data found in the table '$table_name'.");
return;
}
$output = fopen('php://output', 'w');
// Output CSV header
$header = array_keys($results[0]);
fputcsv($output, $header);
// Output CSV rows
foreach ($results as $row) {
fputcsv($output, $row);
}
fclose($output);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment