簡體   English   中英

將 javascript 添加到 wordpress 的“正確”方法是什么?

[英]What's the 'right' way to add javascript to wordpress?

我在functions.php 中有一個函數正在排隊我的script.js。 一切正常。 但是,我只希望該腳本在 single.php 上運行。 現在它在每一頁上運行。 有沒有辦法“控制”腳本應該在哪個頁面上運行?

我的函數如下所示:

function mytheme_script_enqueue() {
    wp_enqueue_style('customstyle', get_template_directory_uri() . '/style.css', array(), '1.0.0');
    wp_enqueue_script('customjs', get_template_directory_uri() . '/assets/js/script.js', array(), '1.0.0');
}

add_action( 'wp_enqueue_scripts', 'mytheme_script_enqueue' );

您可以在函數中添加 if 語句。 見下文:

function mytheme_script_enqueue() {
        wp_enqueue_style('customstyle', get_template_directory_uri() . '/style.css', array(), '1.0.0');
        if(is_single()){ //or any way to target the page you want
            wp_enqueue_script('customjs', get_template_directory_uri() . '/assets/js/script.js', array(), '1.0.0');
        }
    }    
add_action( 'wp_enqueue_scripts', 'mytheme_script_enqueue' );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM