WordPress download of custom CSV file blank

I have a Javascript download function that provides the download of a CSV file from a custom table of a specific page that is private.

The function works perfectly, if the user is logged as an Admin, in case the user is logged with any other WordPress role the CSV file is blank, downloaded with no information.

Since the page is private, the content of the page is visible only for higher roles, but not even those are able to proceed with the download.

Somethings I’ve already tried:

Add the Javascript function directly in the PHP archive that it will be used.
Add the function via the Theme Options Cold Fields (the theme being used is Avada).
Create a new .js file with the function in my child theme and add it to the wp_enqueue_script in the functions file.
Changing the page visibility to public.

With all the above options the result was the same, the download works (with data) only with admin credentials.

What I need is a download file containing all the data that is visible on the table printed in the page, despite of the user being an admin or not.

Current code called at onclick:

var filename_dwn = ‘dados_inscricao.csv’;

function setFileName(){
var input = document.getElementById(“fileName”);
var ext = ‘.csv’;
var filename = input.value;
filename_dwn = filename+ext;

function downloadCSV(csv, filename) {
var csvFile;
var downloadLink;
csvFile = new Blob([csv], {type: “text/csv”});
downloadLink = document.createElement(“a”);
downloadLink.download = filename;
downloadLink.href = window.URL.createObjectURL(csvFile);
downloadLink.style.display = “none”;

function exportTableToCSV() {
var filename = filename_dwn;
var csv = [];
var rows = document.querySelectorAll(“table tr”);

for (var i = 0; i < rows.length-2; i++) {
var row = [], cols = rows[i].querySelectorAll(“td, th”);

for (var j = 0; j < cols.length; j++){
var data = cols[j].innerText.replace(/”/g, ‘””‘);
data = ‘”‘ + data + ‘”‘;
downloadCSV(csv.join(“rn”), filename);

function my_theme_scripts_function() {
wp_enqueue_script( ‘myscript’, get_stylesheet_directory_uri() . ‘/js/scripts.js’);

Read more here:: WordPress download of custom CSV file blank

Leave a Reply

Your email address will not be published. Required fields are marked *