WordPress CSV Reader plugin
Recently, a friend asked me to help with writing a WordPress plugin to print labels.
The idea is to read a CSV file with a set of labels and numbers. This CSV file will be regularly updated and placed in a directory. The system user should be able to view the list of labels and click on a print button, which would prompt a print option that will be used to print the label.
The code
I will be using Lando WordPress recipe to set up a docker instance.
The .yml file is as below. Please check out their documentation for more info on this. I will add the resources at the end of this article.
name: csv
recipe: wordpress
config:
php: '7.4'
composer_version: 2.0.7
via: 'apache:2.4'
webroot: .
database: 'mysql:5.7'
xdebug: true
config:
database: wordpress
username: wordpress
password: wordpress
host: database
port: 3306
Now that we created a WordPress instance, let's create a new plugin folder under /wp-content/plugins
path and name the folder as csv-reader-plugin
.
The main logic will be placed in csv-reader-plugin.php
file. I will explain the meaning of some of the code snippets after.
<?php
/**
* Plugin Name: CSV Reader Plugin
* Plugin URI: #
* Description: Reads a column from a CSV file and displays the content in a WordPress interface
* Version: 1.0
* Author: PG
*/
require_once ABSPATH . 'wp-admin/includes/file.php';
// Hook into WordPress initialization.
add_action('init', 'csv_reader_init');
// Enqueue the JavaScript file.
add_action('wp_enqueue_scripts', 'csv_reader_enqueue_scripts');
function csv_reader_enqueue_scripts()
{
// Enqueue the JavaScript file
wp_enqueue_script('csv-reader-script', plugins_url('js/script.js', __FILE__), array(), '1.0', true);
// Enqueue the Styles file
wp_enqueue_style('csv-reader-style', plugins_url('css/style.css', __FILE__), array(), '1.0');
}
function csv_reader_init()
{
// Create a new page in WordPress to display the imported content.
$page_title = 'CSV Reader Page';
$page_content = '[csv_reader_content]';
$page_check = get_page_by_title($page_title);
// Create the page if it doesn't exist.
if (!$page_check) {
$page_args = array(
'post_title' => $page_title,
'post_content' => $page_content,
'post_status' => 'publish',
'post_type' => 'page',
);
wp_insert_post($page_args);
}
// Register the shortcode to display the imported content
add_shortcode('csv_reader_content', 'csv_reader_display_content');
}
function csv_reader_display_content()
{
// Location of the file that needs to be read.
$file_path = plugin_dir_path(__FILE__).'/test_csv.csv';
// Check if the file exists
if (file_exists($file_path)) {
// Read the CSV file
$csv_data = array_map('str_getcsv', file($file_path));
$content = '<ul>';
$count = 0;
foreach($csv_data as $data => $value) {
$content .= '<li class=\'row '.$value[0].'\' >';
$content .= '<span>' . $value[0] . '</span>'.' '.'<label id=\''.$value[0].'\'>'. $value[1] .'</label>  ';
$content .= '<input class=\'hide\' type="button" onclick="printDiv(\''.$value[0].'\')" value="Print"/>';
$content .= '</li>';
}
$content .= '</ul>';
// Add an update button
$content .= '<button id="csv-reader-update-btn">Update Content</button>';
// JavaScript to handle the button click event
$content .= '<script>
document.getElementById("csv-reader-update-btn").addEventListener("click", function() {
location.reload(); // Reload the page to update the content
});
</script>';
return $content;
} else {
return 'CSV file not found.';
}
}
For the plugin to work, first we need to hook in to WP init
process. And then tell it to look for the function csv_reader_init()
add_action('init', 'csv_reader_init');
And we also tell WP to add our JS and CSS files. To do that, we need to use the wp_enqueue_scripts
hook and pass our function csv_reader_enqueue_scripts()
add_action('wp_enqueue_scripts', 'csv_reader_enqueue_scripts');
csv_reader_init()
is simply telling WP to create a Page and populate the page content via a short code
$page_content = ‘[csv_reader_content]’;
So we need to tell WP to create a short code named csv_reader_content
and tell it to look for csv_reader_display_content()
function.
add_shortcode('csv_reader_content', 'csv_reader_display_content');
And in that csv_reader_display_content()
function we provide the logic to find our CSV data file and read it.
$file_path = plugin_dir_path(__FILE__).'/test_csv.csv';
To use the plugin_dir_path()
we need to require WP file.php. Which we have added at the start of the code.
require_once ABSPATH . 'wp-admin/includes/file.php';
The rest of the code in csv_reader_display_content()
is straightforward.
$csv_data = array_map('str_getcsv', file($file_path));
It reads the data in the CSV file and creates an unordered list. It is important keep note of the element id and class attributes here and adjust them to your advantage.
Within the foreach loop we add a JS function printDiv()
that is hosted in the script.js
file.
$content .= '<input class=\'hide\' type="button" onclick="printDiv(\''.$value[0].'\')" value="Print"/>';
I have used wp_enqueue_script()
and wp_enqueue_style()
to import JS and CSS files that are needed for the functionality of this plugin.
The script.js
will host a code that is triggered upon clicking on Print
button. It will add and remove a CSS class section-to-print
that will help to isolate the HTML element having the label text that needs to be printed, while hiding the rest of the page content.
Below is the JS file which I’ve placed at /wp-content/plugins/csv-reader-plugin/js/script.js
path
function printDiv(id) {
// Clear previously printed element.
const elem = document.getElementById("section-to-print");
if (elem) {
elem.removeAttribute('id');
}
// Print new element.
let parent = document.getElementById(id).parentElement;
let printContents = id + ' ' + document.getElementById(id).innerHTML;
parent.id = 'section-to-print';
window.print();
window.close();
}
The styles for the plugin is located at wp-content/plugins/csv-reader-plugin/css/style.css
@media print {
body,
.hide {
visibility: hidden;
}
#section-to-print {
visibility: visible;
position: absolute;
left: 0;
top: 0;
}
}
Since we are not using any database connection, we completely rely on the sanity of the data in the CSV file. Every time the CSV Reader Page is refreshed, the data is populated using the CSV file.
The UI will look something like this;
And when you click on Print button in front of 4000308 Label 3
below popup should appear;
This is just a very basic and a simplified code that showcase the core functionality, and you can alter it as you like to make it work for you.