How I can add my JQuery script into single wordpre

2019-08-03 23:10发布

问题:

I want to add my JQuery script into single Wordpress page, but I dont know how. Example of script I'd like to inject:

<script type="text/javascript">
    $(document).ready(function() {
        $("html, body").animate({ scrollTop: $(window).height() }, 600);

        return false;
    });
</script>

This code works fine when injected in plain HTML, but how can I do the same for Wordpress?

回答1:

you have a couple of options, the function you created above will add it to all pages (you were registering the script but not actually calling it, thats why its not working. see correction below).

If you want you can simply place the wp_enqueue_script() function below in your template (without add action and the custom() function

or directly write it into the template file (lots of arguments about whether this is acceptable coding practice, but it works)

or require_once / include_once the file in the correct sequence (you are using document.ready so you can do this anywhere below the header (if you already have jquery loaded in the header, if in the footer, must be below the footer) same rules apply for directly writing into the file.

 function custom() { 

 wp_enqueue_script('jquery'); 
 wp_enqueue_script('add-custom-js' , get_template_directory_uri() . '/js/custom.js' , array('jquery'),'',true ); 
 } 
 add_action('wp_enqueue_scripts' . 'custom' );
  • also WP uses non conflict jquery so you need to use jQuery instead of the the shorthand vers $. there are a few alternative ways to use the shorthand if you google it.


回答2:

Personally I feel the best way for adding a JavaScript to a particular page/post is to use ShortCode

Add this:

function add_my_script() {
    return "<script>
                 //your jQuery here
            </script>";
}  
 add_shortcode( 'myCustomShortCode', 'add_my_script' );  

to your function.php file. Your function.php file is location at /wp-content/themes/<name of theme>/

NOTE: Use ' instead of " in your <script> to continue inside the return statement.

Now simply add the shortcode [myCustomShortCode] in your page.



回答3:

just edit a page in wordpress, select text view (not formatted text) and paste your script wherever you like.



标签: wordpress