Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Created August 9, 2018 13:10
Show Gist options
  • Save tommcfarlin/2969c83cef4a946fa6c82b2f3bb1226d to your computer and use it in GitHub Desktop.
Save tommcfarlin/2969c83cef4a946fa6c82b2f3bb1226d to your computer and use it in GitHub Desktop.
[WordPress] On Writing Readable WordPress Functions
$.get(ajaxurl, {
'action': 'getDetails',
'security': $('input[name="acme-security-nonce"]').val()
}, function(response) {
if (false === response.success) {
// Handle the case when the request wasn't successful.
}
// Work with the information that was returned in the response.data property.
});
<?php
/**
* @return bool true if we're able to make Ajax requests; otherwise, false
*/
private function verifyRequest()
{
return
isset($_GET['security']) &&
wp_verify_nonce(strip_tags(stripslashes($_GET['security'])), 'getDetails');
}
<?php
/**
* @return bool true if there are details; false, otherwise
*
* @access private
*/
private function doDetailsExist()
{
return (new WP_Query([
'post_type' => 'acme_post_type',
'post_status' => 'publish',
]))->have_posts();
}
<?php
/**
* @return array a numerically indexed array of all detail IDs
*/
private function getDetailIds(): array
{
global $wpdb;
$results = $wpdb->get_results(
$wpdb->prepare("
SELECT meta_value
FROM $wpdb->postmeta
WHERE meta_key = %s
ORDER BY meta_value ASC
", 'acme_detail_number'),
ARRAY_N
);
$detailIds = [];
array_push($detailIds, array_map(function ($result) {
return $result[0];
}, $results));
return $detailIds[0] ?? $detailIds;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment