I want a script in my theme, ajax.php, which I want to load or access from other frontend pages using ajax.
In ajax.php I want access to core WP functions such as get_posts(), do_shortcode() etc. I.e. I need WordPress loaded on the script.
Traditionally I have setup a page in the admin and given it a custom template so then for my ajax requests I can send to www.site.com/ajax and the custom template handles the request. While this works fine I’m pretty sure this is not the most efficient, or safest way of handling ajax on WP frontend but not sure how to do it properly.
Thanks.
It is really not best practice to do it this way at all. In fact you don’t need to create an ajax.php file unless you’re just going to include it in your functions.php file. You need to read up on AJAX in WordPress. You would just add an action on ‘wp_ajax_name_of_action’ and just specify the action within the javascript ajax function.
Simple example from the WordPress codec:
See the codex page on how to properly use AJAX in plugins. The same actions will work in a theme’s functions.php as well.
Also see this blog post linked on the above codex page for more code samples.