Satch3000
Satch3000

Reputation: 49384

JQuery / PHP in WP plugin

I am trying to run this JQuery in a WP plugin...

<?php

function process_post(){

    wp_enqueue_script('namespaceformyscript', 'http://code.jquery.com/jquery-1.9.1.min.js', array('jquery'));

    ?>

    <script type="text/javascript" >
        jQuery(document).ready(function($) {

            alert('hello');
        });
    </script>

    <?php

}

add_action('init', 'process_post');


?>

This alert is just not happening...

What I'm I doing wrong?

Upvotes: 0

Views: 45

Answers (1)

CodeVirtuoso
CodeVirtuoso

Reputation: 6438

As for calling jQuery, this should be enough:

wp_enqueue_script('jquery');

This assures that even if multiple plugins will call jquery (and they likely will) - that it's not loaded multiple times.

Secondly, you're not using the right hook. From the docs about the init hook:

Runs after WordPress has finished loading but before any headers are sent. 

(http://codex.wordpress.org/Plugin_API/Action_Reference/init)

As a complete solution, try this (untested, should work though):

<?php


load_scripts() {
  wp_enqueue_script('jquery');

  wp_enqueue_script('yourcustomjavascript.js',
  WP_PLUGIN_URL.'/yourpluginfolder/yourcustomjavascript.js',
  array('jquery'));

} 

add_action('admin_enqueue_scripts', 'load_scripts');

By calling scripts like this, you've loaded jQuery and made sure it's not loaded multiple times (by your plugin and some other etc.) You've also made sure that jQuery is loaded before yourcustomjavascript.js as you told WP that it depends on jQuery.

http://codex.wordpress.org/Function_Reference/wp_enqueue_script

Now...your jQuery code will work in both html templates, as well as yourcustomjavascript.js file which you can create.

Upvotes: 1

Related Questions