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.