0

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 ?>

2 Answers 2

4

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>'));

2
  • Thanks Jan, does <b>$&</b> become <b>jQuery&</b> ?
    – Scott B
    Commented Nov 3, 2010 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
    Commented Nov 3, 2010 at 20:17
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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