How to use jQuery within a WordPress plugin

This is just a short sample which shows how you can use jQuery within your own WordPress plugin to make cool JSON requests on PHP pages.

…/wp-content/plugins/your_plugin/your_plugin.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
add_action('template_redirect', 'ypAddMediaFiles');
add_shortcode('your_plugin', 'ypAddShortCode');
...
function ypAddMediaFiles()
{
  wp_enqueue_script('jquery');
  wp_register_script('your_javascript', plugins_url('js/your_javascript.js', __FILE__), array('jquery'));  
}
 
function ypAddShortCode()
{
  wp_enqueue_script('your_javascript');
  return 'JavaScript has been loaded.';
}

…/wp-content/plugins/your_plugin/js/your_javascript.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
your_function('Benny', 'Neugebauer');
 
function your_function(first_name, last_name)
{
  jQuery(document).ready(function($)
  {
    $.post("wp-content/plugins/your_plugin/something_that_gives_you_json.php", 
    {
      param1: first_name,
      param2: last_name
    },
    function(data) 
    {
      var results = jQuery.parseJSON(data);
      alert(results);
    });
  });
}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.