在某些WordPress页面上包含JavaScript的最佳实践

问题描述 投票:0回答:1

我需要在我的WordPress网站的某些特定页面上包含一个JavaScript文件。我目前正在处理的方式是我将所有页面的父节点都归结到特定的父页面,并将JavaScript包含在具有指定父节点的页面上。

这有效,但看起来有点笨重。有没有更好的方法在基本上任意的页面上包含JavaScript文件?

以下是我目前正在使用的内容,让您了解我正在寻找的内容:

function include_crm_wp_funcs(){
  global $post;
  if( get_the_title($post->post_parent) == 'My Parent Page' ){
    require_once 'myJavaScript.js';
  }
}
add_action('wp_enqueue_scripts','include_crm_wp_funcs');
javascript wordpress
1个回答
1
投票
function include_crm_wp_funcs(){
  global $post;
  if( get_the_title($post->post_parent) == 'My Parent Page' ){
     wp_register_script( 'js_name', get_template_directory_uri() . 'PATH TO YOUR JS FILE' );
     wp_enqueue_script( 'js_name' );
  }
}
add_action('wp_enqueue_scripts','include_crm_wp_funcs');

您需要将javascript文件放在主题目录中,并使用wp_register_script()wp_enqueue_script调用它。

© www.soinside.com 2019 - 2024. All rights reserved.