I wrote a plugin that displays all products in a woocommerce store in admin settings option, now I want to add a link to download the products as CSV file.
The problem is, when I click the link I get a permission error saying I don’t have permission to view this page.
Here’s my code:
function extra_tablenav($which) {
if ($which == "top") {
echo '<h3 style="display:inline">'
. __('These products are currently in the database:')
. '</h3>' .
' ' .
'<a href="' . admin_url('admin.php?page=download_csv.php') . '" rel="nofollow noreferrer noopener">' . __('Export to CSV') . '</a>';
}
}
How can I fix those permissions?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Do not point the URL to admin.php, use admin-post.php instead:
'<a href="' . admin_url( 'admin-post.php?action=print.csv' ) . '" rel="nofollow noreferrer noopener">'
In your plugin register a callback for that action:
add_action( 'admin_post_print.csv', 'print_csv' );
function print_csv()
{
if ( ! current_user_can( 'manage_options' ) )
return;
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
// output the CSV data
}
If you want to make the data available for anonymous users (not logged in), then register the callback again with:
add_action( 'admin_post_nopriv_print.csv', 'print_csv' );
… and remove the capability check from the function.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0