This Export to CSV plugin for WooCommerce simplifies the process of exporting product data from your store. In this article, we’ll dissect the plugin’s code to understand how it achieves seamless data exports and explore its key features.
Plugin Integration with WordPress
The first critical aspect of any WordPress plugin is its integration into the WordPress ecosystem. The Export to CSV plugin achieves this by adding a submenu item under the WooCommerce menu in the WordPress admin dashboard. This makes it easily accessible to administrators without cluttering the interface.
// Add export submenu item under WooCommerce menu
function woocommerce_export_csv_menu() {
add_submenu_page(
'woocommerce',
'Export to CSV',
'Export to CSV',
'manage_options',
'woocommerce-export-csv',
'woocommerce_export_csv_page'
);
}
add_action('admin_menu', 'woocommerce_export_csv_menu');
Explanation:
- Function
woocommerce_export_csv_menu()
: This function defines a WordPress action hookadmin_menu
that adds a submenu page to the WooCommerce menu. add_submenu_page()
: This WordPress function adds a submenu page under the ‘woocommerce’ menu. The parameters passed include:'woocommerce'
: Parent menu slug.'Export to CSV'
: Page title displayed in the admin menu.'Export to CSV'
: Menu title displayed in the submenu.'manage_options'
: Capability required to access this menu item.'woocommerce-export-csv'
: Unique slug for this submenu page.'woocommerce_export_csv_page'
: Callback function that renders the content of the submenu page.
Initiating the Export Process
Once administrators navigate to the ‘Export to CSV’ submenu page, they can trigger the export process by clicking a button or link. The plugin responds to this action by preparing and outputting CSV data containing detailed product and category information.
// Export callback function
function woocommerce_export_csv_page() {
if (!current_user_can('manage_options')) {
return;
}
// Check if export action is triggered
if (isset($_GET['export']) && $_GET['export'] === 'true') {
ob_clean(); // Clean output buffer
// Set headers for CSV download
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="woocommerce-export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
// Output CSV content directly to PHP output
$output = fopen('php://output', 'w');
// Headers for products
$product_headers = array(
'Name',
'SKU',
'Categories',
'Short Description',
'Description',
'Status',
'Manufacturer',
'Tax Class',
'Product ID',
'Product Type',
'Price',
'Special Price',
'Special Price From',
'Special Price To',
'Meta Title',
'Meta Keywords',
'Meta Description',
'URL Key',
'Weight',
'Width',
'Height',
'Length',
'Related Products',
'Product Tags',
'EAN',
'UPC',
'Attributes',
'Product Options',
'Product Filter',
'Downloadable Products',
'Thumbnail Image',
'Additional Images',
'Stock Availability',
);
// Output headers to CSV file
fputcsv($output, $product_headers);
// Export products
$products = get_posts(array(
'post_type' => 'product',
'posts_per_page' => -1,
));
// Prepare product data and output to CSV
foreach ($products as $product) {
setup_postdata($product);
// Get product categories
$categories = get_the_terms($product->ID, 'product_cat');
$category_names = array();
if (!empty($categories)) {
foreach ($categories as $category) {
$category_names[] = $category->name;
}
}
$categories_str = implode(', ', $category_names);
// Get product data
$product_id = $product->ID;
$product_obj = wc_get_product($product_id);
$product_type = $product_obj->get_type();
// Get cover product image URL
$cover_image_url = '';
if (has_post_thumbnail($product_id)) {
$cover_image_url = get_the_post_thumbnail_url($product_id, 'full'); // Use 'full' for the full-size image URL
}
// Get additional images information
$additional_images = array();
// Get product gallery images
$product_gallery_ids = get_post_meta($product_id, '_product_image_gallery', true);
if (!empty($product_gallery_ids)) {
$attachment_ids = explode(',', $product_gallery_ids);
foreach ($attachment_ids as $attachment_id) {
$attachment_url = wp_get_attachment_url($attachment_id);
if ($attachment_url) {
$additional_images[] = $attachment_url;
}
}
}
$additional_images_str = implode(', ', $additional_images);
// Get downloadable product information
if (function_exists('wc_get_product_downloads')) {
// Use wc_get_product_downloads() if available
$downloads = wc_get_product_downloads($product_id);
$downloadable_products = array();
foreach ($downloads as $download) {
// Encode each field to UTF-8
$downloadable_products[] = mb_convert_encoding($download['name'], 'UTF-8', 'UTF-8');
}
$downloadable_products_str = implode(', ', $downloadable_products);
} else {
// Fallback method to retrieve downloadable product information
$downloadable_products = array();
$product_downloads = get_post_meta($product_id, '_downloadable_files', true);
if (!empty($product_downloads)) {
foreach ($product_downloads as $download) {
// Encode each field to UTF-8
$downloadable_products[] = mb_convert_encoding($download['name'], 'UTF-8', 'UTF-8');
}
}
$downloadable_products_str = implode(', ', $downloadable_products);
}
// Get related products
if (function_exists('wc_get_product_related')) {
// Use wc_get_product_related() to get related product IDs
$related_product_ids = wc_get_product_related($product_id);
} else {
// Fallback to direct database query if wc_get_product_related() is not available
global $wpdb;
$related_product_ids = $wpdb->get_col(
$wpdb->prepare("
SELECT p2p.p2p_to AS related_product_id
FROM {$wpdb->prefix}posts p
LEFT JOIN {$wpdb->prefix}p2p p2p ON p.ID = p2p.p2p_from
WHERE p.post_type = 'product'
AND p.post_status = 'publish'
AND p.ID = %d
AND p2p.p2p_type = 'related'
", $product_id)
);
}
// Prepare product data
$product_data = array(
get_the_title($product_id), // Product name
$product_obj->get_sku(), // SKU
$categories_str, // Categories
$product_obj->get_short_description(), // Short Description
$product_obj->get_description(), // Description
$product_obj->get_status(), // Status
$product_obj->get_attribute('manufacturer'), // Manufacturer
$product_obj->get_tax_class(), // Tax Class
$product_id, // Product ID
$product_type, // Product Type
$product_obj->get_price(), // Price
$product_obj->get_sale_price(), // Special Price
$product_obj->get_date_on_sale_from(), // Special Price From
$product_obj->get_date_on_sale_to(), // Special Price To
$product_obj->get_meta('meta_title'), // Meta Title
$product_obj->get_meta('meta_keywords'), // Meta Keywords
$product_obj->get_meta('meta_description'), // Meta Description
$product_obj->get_slug(), // URL Key
$product_obj->get_weight(), // Weight
$product_obj->get_width(), // Width
$product_obj->get_height(), // Height
$product_obj->get_length(), // Length
implode(', ', $related_product_ids), // Related Products
implode(', ', wp_get_post_terms($product_id, 'product_tag', array('fields' => 'names'))), // Product Tags
$product_obj->get_meta('ean'), // EAN
$product_obj->get_meta('upc'), // UPC
implode(', ', array_keys($product_obj->get_attributes())), // Attributes
implode(', ', $product_obj->get_formatted_variation_attributes()), // Product Options
implode(', ', $product_obj->get_meta('product_filter')), // Product Filter
$downloadable_products_str, // Downloadable Products
$cover_image_url, // Thumbnail Image
$additional_images_str, // Additional Images
$product_obj->is_in_stock() ? 'In Stock' : 'Out of Stock', // Stock Availability
);
// Output product data to CSV file
fputcsv($output, $product_data);
}
// Close output file
fclose($output);
// Prevent any more content from being sent to the browser
exit;
}
// Display export button/link in the admin page
echo '<div class="wrap">';
echo '<h1>Export Products to CSV</h1>';
echo '<p><a href="' . esc_url(add_query_arg('export', 'true')) . '" class="button button-primary">Export Products</a></p>';
echo '</div>';
}
Explanation (continued):
- Export Callback Function (
woocommerce_export_csv_page()
):- Access Control (
current_user_can('manage_options')
): Ensures that only users with sufficient permissions (in this case,manage_options
) can access and trigger the export functionality. - Export Trigger (
isset($_GET['export']) && $_GET['export'] === 'true'
): Checks if the export action is triggered via the URL query parameter. - Output Buffer (
ob_clean()
): Clears any previous output buffer to ensure clean and uninterrupted CSV output. - Headers for CSV (
header()
Functions): Sets necessary HTTP headers to indicate that the response is a CSV file for download. - CSV Output Stream (
fopen('php://output', 'w')
): Opens a writable handle to PHP’s output stream, facilitating direct CSV data output. - Product Headers (
$product_headers
): Defines an array containing column headers for the product CSV file, ensuring clarity and structured data output. - Product Query (
get_posts()
): Retrieves all products ('post_type' => 'product'
) to be exported from the WooCommerce store. - Loop through Products (
foreach ($products as $product) { ... }
): Iterates over each product to gather and format its data for CSV export. - Fetching Product Categories (
get_the_terms()
): Retrieves and formats product category names associated with each product. - Product Data Retrieval (
wc_get_product()
andget_post_meta()
): Utilizes WooCommerce and WordPress functions to fetch various product attributes, such as SKU, description, pricing, meta information, and more. - Handling Product Images and Downloads: Retrieves and formats primary and additional images, as well as downloadable product information, ensuring comprehensive data export.
- Handling Related Products (
wc_get_product_related()
and direct database query): Retrieves related product IDs to maintain product relationships in the CSV export. - Preparing Product Data (
$product_data
): Constructs an array containing specific fields of product data formatted for CSV export. - Outputting Product Data (
fputcsv($output, $product_data)
): Writes each product’s data to the CSV output stream. - Closing Output File (
fclose($output)
): Ensures proper closure of the CSV output file handle after all product data is exported. - Exiting Script Execution (
exit
): Prevents any further content from being sent to the browser after the CSV export is complete.
- Access Control (
Final Thoughts
The Export to CSV plugin for WooCommerce stands out as a robust tool for efficiently exporting comprehensive product data from WooCommerce stores to other platforms such as AspectCart. By dissecting its code and understanding each component, administrators and developers gain insight into its inner workings and can leverage its capabilities to streamline data management tasks effectively.
Next time you need to export product data from your WooCommerce store, consider using the Export to CSV plugin to ensure seamless and structured data exports.
Written by Dimitrios S. Sfyris, developer and founder of AspectSoft, a software company specializing in innovative solutions. Follow me on LinkedIn for more insightful articles and updates on cutting-edge technologies.
Subscribe to our newsletter!
+ There are no comments
Add yours