Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active Sep 21, 2017
Embed
What would you like to do?
[WordPress] Download User Email Addresses via JSON in WordPress
<?php
public function addSubmenuPage()
{
\add_submenu_page(
'tools.php',
'Export Emails',
'Export Emails',
'manage_options',
'acme-export-emails',
'exportEmails'
);
}
<?php
public function addJavaScript()
{
if (!current_user_can('manage_options')) {
return;
}
wp_enqueue_script(
'acme-email-export-admin',
$this->plugin_url . 'Emails/assets/scripts/exportEmail.js',
array('jquery')
);
wp_localize_script(
'acme-email-export-admin',
'acme_email_export',
array(
'ajax_url' => admin_url('admin-ajax.php'),
'security' => wp_create_nonce('acme-email-export-nonce')
)
);
}
$('a[href="tools.php?page=acme-export-emails"]').on('click', function(evt){
evt.preventDefault();
_getEmailAddresses($(this));
});
var _getEmailAddresses = function($elem) {
$.get(acme_email_export.ajax_url, {
security: acme_email_export.security,
action: 'getEmailAddresses'
}, function(response) {
if ( '' === response ) {
return;
}
// TODO...
});
};
<?php
private function getUserResults()
{
$query = new \WP_User_Query(
array(
'role_in' => array('administrator','subscriber')
)
);
return $query->get_results();
}
<?php
private function getUserInfo($results)
{
$user_info = array();
foreach ($results as $result) {
if (isset($result->user_email)) {
array_push($user_info, $result->user_email);
}
}
return $user_info;
}
<?php
private function writeAddressesToDisk($addresses)
{
$path = plugin_dir_path(__FILE__) . 'results.json';
if (!file_exists($path)) {
touch($path);
}
$handle = fopen($path, 'w');
fwrite($handle, json_encode($addresses));
fclose($handle);
}
<?php
public function getEmailAddresses()
{
$this->writeAddressesToDisk(
$this->getUserInfo(
$this->getUserResults()
)
);
echo plugin_dir_url(__FILE__) . 'results.json';
die;
}
var _getEmailAddresses = function($elem) {
$.get(acme_email_export.ajax_url, {
security: acme_email_export.security,
action: 'getEmailAddresses'
}, function(response) {
if ( '' === response ) {
return;
}
// Creates the element to download the file.
$('<a/>')
.attr('href', response)
.attr('download', 'response.json')
.attr('id', 'acme-download-emails')
.text('Download')
.attr('style', 'display:none')
.appendTo($elem.parent());
// Manually trigger clicking of the hidden element to download the file.
$('#acme-download-emails')[0].click();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment