简体   繁体   English

在某些WordPress页面上包含JavaScript的最佳做法

[英]Best practice for including a JavaScript on certain WordPress pages

I need to include a JavaScript file on certain specific pages of my WordPress site. 我需要在WordPress网站的某些特定页面上包含一个JavaScript文件。 The way I'm handling in currently is that I'm parenting all the pages to a particular parent page, and including the JavaScript on pages that have the specified parent. 目前,我正在处理的方式是将所有页面作为一个特定的父页面的父对象,并包括具有指定父对象的页面上的JavaScript。

This works, but it seems a little clunky. 这可行,但似乎有些笨拙。 Is there a better way to include a JavaScript file on an essentially arbitrary set of pages? 是否有更好的方法将JavaScript文件包含在基本上任意的一组页面上?

Here's what I'm using currently, to give you an idea of what I'm looking for: 这是我目前正在使用的内容,可让您大致了解我要寻找的内容:

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');
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');

You need to put the javascript file in your theme directory and call it using wp_register_script() and wp_enqueue_script . 您需要将javascript文件放在主题目录中,并使用wp_register_script()wp_enqueue_script进行调用

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

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