Note that there are some explanatory texts on larger screens.

plurals
  1. POCalling json function in wordpress
    text
    copied!<p>In my wordpress plugin I need to have a JSON option to load, using jquery, info about a custom post type. This jquery call will come in a page where all users should see it. </p> <p>as far as i understand from the <a href="http://codex.wordpress.org/AJAX_in_Plugins" rel="nofollow">codex</a> I should have a function:</p> <pre><code>function my_json_returning_function(){ // get json objects here echo $json; die(); } </code></pre> <p>As well as the actions:</p> <pre><code>add_action('wp_ajax_my_json_action', 'my_json_returning_function'); add_action('wp_ajax_nopriv_my_json_action', 'my_json_returning_function'); </code></pre> <p>All in my plugin file. </p> <p>then something like:</p> <pre><code>jQuery(document).ready(function($) { var data = { action: 'my_json_action', }; // since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php jQuery.post(&lt;?php echo admin_url('admin-ajax.php');?&gt;, data, function(response) { alert('Got this from the server: ' + response); }); }); </code></pre> <p>should call the function in question. </p> <p>My real question is where i should place all the different parts - and if something is missing.</p> <p>The php function and the actions hooks go into the plugin file. But the javascript I am more confused about. I want to put it in the plugin javascript file, but since i have to fetch the admin url using php that becomes a problem. </p> <p>Also how do I make sure that the script is only called if in a certain page? Are there more hooks and filters I should be comfortable with? Or is it possible to load it using wp_enqueue_script when executing a shortcode on that page, or is that to late, as I would seem it needs to be loaded in the header. </p> <p>A lot of questions, but I hope you understand the basis of my problem - I have a hard time placing the code in the right places in the wordpress structure.</p> <p><strong>EDIT:</strong> Calling echo admin_url('admin-ajax.php'); is not, at least in my eyes the most elegant way of doing it. I'd rather have a json API, with its seperate url, and calling it in the ajax call. How would I go about setting up a page in wordpress that only returns a json object?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload