We recently designed a developed a site for an international company that has locations in the US, Mexico, and Canada. To be able to manage these locations easily and view them in an embedded map on the frontend we created a ‘Locations’ custom post type that has a few custom ACF fields for the location’s details. We then developed a module that queries the locations and returns the location results as a JSON object. When a browser receives that JSON object JavaScript iterates through each location and adds a marker to a Google Map using the Google Maps API.
We firmly believe in best practices – and one of the best practices in WordPress development is to follow their codex recommendations and use WordPress hooks and actions. While strategizing this module, we discovered the native WordPress Ajax actions.
During development, we hit a ‘snag’. The Ajax call would return an error if the user was not logged in. After Googling for solutions, two of our developers tried everything from localizing the ajax script and adding the ajaxurl
variable to the frontend using the wp_footer
action. After several hours of reading through solutions posted by the WordPress community and daydreaming about the entire internet burning to the ground, we realized something extremely obvious in the WordPress codex. There is a variation of the wp_ajax_
action named wp_ajax_nopriv_
that is specifically for creating Ajax actions for users that are not logged in.
How it all comes together.
At the end of this discovery, we quickly were able to fix the issue and finished developing the module in minutes. There are many suggested answers on Stack Overflow that are not accepted and are not acceptable outright, so we hope our example below helps you create a custom WordPress Ajax endpoint that works for both admins and visitors.
Other Bold Articles
A resource for business owners, marketing departments, developers, and more.