最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

wp enqueue script - How to execute Javascript on a Wordpress page?

programmeradmin0浏览0评论

I'm trying to get some Javascript to run on one of my pages. But nothing I do seems to work. I ran the code in a sandbox and it is functional.

I tried: - Inserting and HTML builder element and putting the code in tags - uploading the .js file in the theme and linking to it in my html code - Multiple script plugins

How does one simply execute Javascript on a Wordpress page?

I'm trying to get some Javascript to run on one of my pages. But nothing I do seems to work. I ran the code in a sandbox and it is functional.

I tried: - Inserting and HTML builder element and putting the code in tags - uploading the .js file in the theme and linking to it in my html code - Multiple script plugins

How does one simply execute Javascript on a Wordpress page?

Share Improve this question edited Jul 10, 2019 at 18:04 Nicolai Grossherr 18.9k8 gold badges64 silver badges109 bronze badges asked Jul 9, 2019 at 5:52 Val.BVal.B 12 bronze badges 1
  • Please show what you tried, optimally with code. It makes giving answers to your specific problem easier. – Nicolai Grossherr Commented Jul 10, 2019 at 18:05
Add a comment  | 

2 Answers 2

Reset to default 2
<?php
function enqueue_javascript_for_certain_page() {

    $page_id = 100; // change this to fit your needs

    if ( is_page( $page_id ) ) { // check the page you are on

        wp_enqueue_script(
            'my_script_name', // script handle
            get_template_directory_uri() . '/js/my-js-file.js', // script URI
            array( // your script is dependent on following:
                'jquery',
                'jquery-ui'
            ),
            NULL, // script version (NULL means no version to display in query string)
            true // load script right before </body> tag
        );

    }

}

add_action( 'wp_enqueue_scripts', 'enqueue_javascript_for_certain_page' );

add js file using function.php

function add_theme_scripts() {
    wp_enqueue_script( 'script', get_template_directory_uri() . '/js/script.js', array ( 'jquery' ), 1.1, true);
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );

or

//if you want to add script in plugin use this code in plugin:
function yourScript() {
    wp_register_script( 'script', plugins_url('js/jqueryfile.js',__FILE__),array('jquery'),'1.1', true );
    wp_enqueue_script('script');
}
add_action( 'admin_enqueue_scripts', yourScript);
发布评论

评论列表(0)

  1. 暂无评论