I would like to use jQuery in my Wordpress plugin. I'm trying to load the jquery library using the enqueue script but its throwing an error.

Error: $ is not a function

Here's the code snippet that's inside my main plugin.php file...

function ($post)
{
    wp_enqueue_script('jquery');
    ?>
    <script type="text/javascript">
    function doTestParse(searchString){
        var rx = new RegExp('(?![^<]+>)'+searchString, "gi");
        $(this).html($(this).html().replace(rx, '<b>$&</b>'));
    }
    </script>
<?php ?>
link|improve this question

feedback

2 Answers

up vote 4 down vote accepted

jQuery is included in noConflict mode in WordPress, so you can't use the shorthand $, but must write jQuery(this).html(jQuery(this).html().replace(rx, '<b>$&</b>'));

link|improve this answer
Thanks Jan, does <b>$&</b> become <b>jQuery&</b> ? – Scott B Nov 3 '10 at 19:56
@Scott: html() returns a Javascript String object, and replace() is a standard function. &$ means "the matched substring" in this context, so the $ has nothing to do with jQuery and has to stay. – Jan Fabry Nov 3 '10 at 20:17
feedback

I am not sure when exactly your code fires, but it is good practice to add enqueue directives to init hook, instead of trying to call them in-place.

wp_enqueue_script docs in Codex have plenty of useful examples on topic.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.