繁体   English   中英

WordPress 通过函数将 JavaScript 添加到一页。php

[英]WordPress add JavaScript just to one page via functions.php

在我的 WordPress 网站的一页上,我使用了一个照片库。 为此,我需要一个 js 文件。 现在 js 文件正在加载到每个页面上,但它只需要一个页面 ID 为 2 的特定页面。现在的问题是,is_page(2) 在函数中不起作用。php 因为当时没有设置页面 ID。 是否仍然可以通过 functions.php 执行此操作,或者您只是在 footer.php 中添加脚本?

function footer_scripts()
{
    // If query if current Page is not wp-login-php or admin page
    if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {

            wp_register_script('photo-gallery', get_template_directory_uri() . '/js/back-layer-photo-gallery.js', array('jquery'), '1.3', true);
            wp_enqueue_script('photo-gallery');
 
    }
}  

add_action('init', 'footer_scripts');

您可以在 function.php 中添加此代码,并用您的页面和脚本的 slug 名称填充它

   // Load  conditional scripts
  function your_conditional_scripts()
  {
  if (is_page('pagenamehere')) {
    wp_register_script('scriptname', get_template_directory_uri() . 
  '/js/scriptname.js', array('jquery'), '1.0.0'); // Conditional 
script(s)
    wp_enqueue_script('scriptname'); // Enqueue it!
}
}

add_action('wp_print_scripts', 'your_conditional_scripts'); // Add 
Conditional Page Scripts

您可以使用页面 slug 而不是页面 ID,并使用“wp_enqueue_scripts”而不是“init”。 如果您使用的是子主题,请使用“get_stylesheet_directory_uri()”代替“get_template_directory_uri()”,否则您可以保持原样。

add_action('wp_enqueue_scripts', 'enqueue_script');
function enqueue_script() {
    if (is_page('page_slug_here')) { // Add slug in condition
        wp_enqueue_script('photo-gallery', get_template_directory_uri().'/js/back-layer-photo-gallery.js', array( 'jquery' ), '1.0', true);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM