WordPress主题制作

  1. 主页
  2. 文档
  3. WordPress主题制作
  4. 引入外部CSS样式文件和JS脚本文件
  5. wp_enqueue_script()

wp_enqueue_script()

函数用法:

<?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>

参数解释:

  • $handle:用于区别 JS 名称,即标识字串 (string);
  • $src:JS 的文件 URL (string);
  • $deps:加载的 JS 所依存的其他 JS 标识字串数组 (array:string, 非必需);
  • $ver:JS 的版本号,留空则使用当前 WP 版本号 (string, 非必需);
  • $in_footer:是否放置到网页 HTML 底部加载 (boolean, 非必需)。

示例:

/**
 * Register and Enqueue Scripts.
 */
function twentytwenty_register_scripts() {

	$theme_version = wp_get_theme()->get( 'Version' );

	if ( ( ! is_admin() ) && is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

	wp_enqueue_script( 'twentytwenty-js', get_template_directory_uri() . '/assets/js/index.js', array(), $theme_version, false );
	wp_script_add_data( 'twentytwenty-js', 'async', true );

}

add_action( 'wp_enqueue_scripts', 'twentytwenty_register_scripts' );

<?php
function my_enqueue_scripts() {
if( !is_admin ) { // 前台加载的脚本与样式表
// 去除已注册的 jquery 脚本
wp_deregister_script( 'jquery' );
// 注册 jquery 脚本
wp_register_script( 'jquery', get_template_directory_uri() . '/js/jquery.js', false, '1.0', false );
// 提交加载 jquery 脚本
wp_enqueue_script( 'jquery' );
 } 
} 
// 添加回调函数到 init 动作上
add_action( 'init', 'my_enqueue_scripts' );
?>

有依赖关系(该js依赖“jquery”):

//全局加载js脚本
wp_enqueue_script( 'twentyfifteen-script', get_template_directory_uri() . '/js/functions.js', array( 'jquery' ), '20141212', true );
     

参考

https://yusi123.com/3086.html

这篇文章对您有用吗?

我们要如何帮助您?