1

I would like to add the following JavaScript function to a wordpress child theme (functions.php). Unfortunately I am not able to make it. Function:

$.fn.cityAutocomplete.transliterate = function (s) { s = String(s); return s; }; 

I tried this:

<?php add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' ); function my_theme_enqueue_styles() { wp_enqueue_style( 'listingpr-parent-style', get_template_directory_uri() . '/style.css' ); } echo "<script>fn.cityAutocomplete.transliterate();</script>"; ?> 

But it dont work. Please help me to fix my issue. Thanks you!

regards shotput_wp

    2 Answers 2

    1

    You can't add the code just by echoing like that. The wp_enqueue_scripts action doesn't work that way.

    So you have two options.

    First option, make a new file called cityautocomplete.js and put it in your child theme directory/folder. In that file paste the following:

    (function( $ ) { 'use strict'; $( document ).ready( function() { $.fn.cityAutocomplete.transliterate = function(s) { s = String(s); return s; }; } ); } )( jQuery ); 

    Then, in your functions.php where you attempted to paste the script, add the following:

    wp_enqueue_script( 'cityautocomplete', get_stylesheet_directory_uri() . 'cityautocomplete.js', array( 'jquery' ), '1.x', true ); 

    (Change the 1.x to match your child theme version number.)

    That's the preferred method. You could/should even consider naming the file something like child.js and then putting any additional javascript/jQuery in there so you're only enqueueing one file rather than a myriad of files with simple bits of JS.

    The second option would be to print out the script contents in the theme head or footer. Paste the following in your functions.php file:

     function cityAutocomplete(){ ?> <script type="text/javascript"> (function( $ ) { 'use strict'; $( document ).ready( function() { $.fn.cityAutocomplete.transliterate = function(s) { s = String(s); return s; }; } ); } )( jQuery ); </script> <?php }; 

    Then depending on if you need it in the <head> tag or if it works better in the footer, use one of these:

    add_action( 'wp_head', 'cityAutocomplete' ); //for <head> inclusion

    add_action( 'wp_footer', 'cityAutocomplete' ); //for footer inclusion

    Don't use both or you'll double up your script.

      0

      Try this:

      add_action("wp_footer","custom_footer_script"); function custom_footer_script(){ ?> <script> //your script here </script> <?php } 

      This will add script to footer

        Start asking to get answers

        Find the answer to your question by asking.

        Ask question

        Explore related questions

        See similar questions with these tags.