如何在WordPress上正确加载Javascript和CSS

html-css014

如何在WordPress上正确加载Javascript和CSS,第1张

下面这个例子在 add_action 钩子中使用 init。使用 init 有两个原因,一是因为我们正在注销WordPress默认的jQuery库,然后加载谷歌的jQuery库;二是确保在WordPress的头部就加载脚本和CSS。

使用if ( !is_admin() )是为了确保这些脚本和css只在前端加载,不会再后台管理界面加载。

/** Google jQuery Library, Custom jQuery and CSS Files */

function myScripts() {

wp_register_script( 'google', 'http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js' )

wp_register_script( 'default', get_template_directory_uri() . '/jquery.js' )

wp_register_style( 'default', get_template_directory_uri() . '/style.css' )

if ( !is_admin() ) { /** Load Scripts and Style on Website Only */

wp_deregister_script( 'jquery' )

wp_enqueue_script( 'google' )

wp_enqueue_script( 'default' )

wp_enqueue_style( 'default' )

}

}

add_action( 'init', 'myScripts' )

加载WP默认 jQuery 库和主题自定义的脚本、样式

第3行:使用 array(‘jquery’) 是为了告诉 WordPress 这个 jquery.js 是依赖WordPress 的jQuery库文件,从而使 jquery.js 在WordPress jQuery库文件后加载。

/** Add Custom jQuery and CSS files to a Theme */

function myScripts() {

wp_register_script( 'default', get_template_directory_uri() . '/jquery.js', array('jquery'), '' )

wp_register_style( 'default', get_template_directory_uri() . '/style.css' )

if ( !is_admin() ) { /** Load Scripts and Style on Website Only */

wp_enqueue_script( 'default' )

wp_enqueue_style( 'default' )

}

}

add_action( 'init', 'myScripts' )

加载 print.css 到你的WordPress主题

第 3 行:最后的 ‘print’是媒体屏幕调用,确保 print.css 在网站的打印机中的文件加载时才加载。

/** Adding a Print Stylesheet to a Theme */

function myPrintCss() {

wp_register_style( 'print', get_template_directory_uri() . '/print.css', '', '', 'print' )

if ( !is_admin() ) { /** Load Scripts and Style on Website Only */

wp_enqueue_style( 'print' )

}

}

add_action( 'init', 'myPrintCss' )

使用 wp_enqueue_scripts 替换 init

如果你要在文章或页面加载唯一的脚本,那就应该使用 wp_enqueue_scripts 替换 init。使用 wp_enqueue_scripts 仅仅只会在前台加载脚本和CSS,不会在后台管理界面加载,所以没必要使用 !is_admin() 判断。

使用 is_single() 只在文章加载脚本或CSS

第 3 行的 # 替换为文章的ID就可以让脚本和css只加载到那篇文章。当然,如果直接使用 is_single() (不填ID),就会在所有文章加载脚本和CSS。

/** Adding Scripts To A Unique Post */

function myScripts() {

if ( is_single(#) ) { /** Load Scripts and Style on Posts Only */

/** Add jQuery and/or CSS Enqueue */

}

}

add_action( 'wp_enqueue_scripts', 'myScripts' )

使用 is_page() 只在页面加载脚本或CSS

第 3 行的 # 替换为页面的ID就可以让脚本和css只加载到那个页面。当然,如果直接使用 is_single() (不填ID),就会在所有页面加载脚本和CSS。

/** Adding Scripts To A Unique Page */

function myScripts() {

if ( is_page(#) ) { /** Load Scripts and Style on Pages Only */

/** Add jQuery and/or CSS Enqueue */

}

}

add_action( 'wp_enqueue_scripts', 'myScripts' )

使用 admin_enqueue_scripts 加载脚本到后台

这个例子将在整个后台管理界面加载脚本和CSS。这个方法不推荐用在插件上,除非插件重建了整个后台管理区。

第 10 行使用 admin_enqueue_scripts 替换了 init 或 wp_enqueue_scripts

第 5、6 行,如果你要自定义后台管理区,你可以需要禁用默认的WordPress CSS调用。

/** Adding Scripts To The WordPress Admin Area Only */

function myAdminScripts() {

wp_register_script( 'default', get_template_directory_uri() . '/jquery.js', array('jquery'), '' )

wp_enqueue_script( 'default' )

//wp_deregister_style( 'ie' )/** removes ie stylesheet */

//wp_deregister_style( 'colors' )/** disables default css */

wp_register_style( 'default', get_template_directory_uri() . '/style.css', array(), '', 'all' )

wp_enqueue_style( 'default' )

}

add_action( 'admin_enqueue_scripts', 'myAdminScripts' )

加载脚本和CSS到WordPress登录界面

第 6 行:我无法弄清楚如何在在登录页面注册/排序 CSS文件,所以这行手动添加样式表。

第 10-14行:用来移除WordPress默认的样式表。

/** Adding Scripts To The WordPress Login Page */

function myLoginScripts() {

wp_register_script( 'default', get_template_directory_uri() . '/jquery.js', array('jquery'), '' )

wp_enqueue_script( 'default' )

?>

<link rel='stylesheet' id='default-css' href='<?php echo get_template_directory_uri() . '/style.css'?>' type='text/css' media='all' />

<?php }

add_action( 'login_enqueue_scripts', 'myLoginScripts' )

/** Deregister the login css files */

function removeScripts() {

wp_deregister_style( 'wp-admin' )

wp_deregister_style( 'colors-fresh' )

}

add_action( 'login_init', 'removeScripts' )

将 jQuery 库移动到页脚

你不能将WordPress默认的jQuery 库移动到页面底部,但是你可以将自定义的jQuery 或其他外部jQuery 库(比如Google的)移动到底部。不要将CSS移动到页面底部。

第 3、4 行:最后的 ‘true’告诉WordPress在页面底部加载这些脚本。

/** Moves jQuery to Footer */

function footerScript() {

wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"), false, '', true )

wp_register_script( 'default', get_template_directory_uri() . '/jquery.js', false, '', true )

if ( !is_admin() ) { /** Load Scripts and Style on Website Only */

wp_deregister_script( 'jquery' )

wp_enqueue_script( 'jquery' )

wp_enqueue_script( 'default' )

}

}

add_action( 'init', 'footerScript' )

根据不用的用户角色和功能加载jQuery和CSS

如果你的网站有作者、编辑和其他管理员,你可能需要通过 jQuery 来为他们显示不同的信息。你需要使用 current_user_can 确定登录的用户的角色和功能 。

下面三个例子中,如果用户已经登录,将在整个网站加载这些脚本和CSS。使用 !is_admin() 包装 enqueue_script 确保只在前台加载,或者在 add_action 使用 admin_enqueue_scripts 就可以确保只在后台管理区加载。

为可以“编辑文章”的管理员加载脚本和CSS

只对超级管理员和网站管理员生效

/** Add CSS &jQuery based on Roles and Capabilities */

function myScripts() {

if ( current_user_can('edit_posts') ) {

/** Add jQuery and/or CSS Enqueue */

}

}

add_action( 'init', 'myScripts' )

为所有登录用户加载脚本和CSS

/** Admins / Authors / Contributors / Subscribers */

function myScripts() {

if ( current_user_can('read') ) {

/** Add jQuery and/or CSS Enqueue */

}

}

add_action( 'init', 'myScripts' )

为管理员以外的已登录用户加载脚本和CSS

/** Disable for Super Admins / Admins enable for Authors / Contributors / Subscribers */

function myScripts() {

if ( current_user_can('read') &&!current_user_can('edit_users') ) {

/** Add jQuery and/or CSS Enqueue */

}

}

add_action( 'init', 'myScripts' )

最后的提示

上面的很多例子如果使用相同的add_action,就可以被合并成一个单一的函数。

换句话说,您可以使用多个 if 语句在一个函数中分裂了你的脚本和CSS调用,如:if_admin!if_admin,is_page,is_single和current_user_can的,因为每次使用相同的add_action的init。

给个例子吧:传几个地图文件到服务器

1)aspx文件:

<%@ Page language="c#" Codebehind="AddMap.aspx.cs" AutoEventWireup="false" Inherits="ZiFengLast.SystemSet.AddMap" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

<HEAD>

<title>MapAdmin</title>

<meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">

<meta content="C#" name="CODE_LANGUAGE">

<meta content="JavaScript" name="vs_defaultClientScript">

<meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">

<LINK href="../StyleSheet1.css" type="text/css" rel="stylesheet">

<script language="javascript">

function AddFile()

{

var rows=document.getElementById("rows").value

var cols=document.getElementById("cols").value

var FileList=document.getElementById("MyFile")

if(document.getElementById("MyFile").innerHTML.toString().length>200)

{

// alert(document.getElementById("MyFile").innerHTML.toString().length)

FileList.innerHTML="<font class='TagTitle'><b>          第1个地图:</b></font><input style='WIDTH: 200pxHEIGHT: 22px' type='file' size='14' name='File'>"

}

for(i=1i<cols*rowsi++)

{

j=i+1

var str ='<font class="TagTitle"><b>          第'+j+'个地图:</b></font><input style="WIDTH: 200pxHEIGHT: 22px" type="file" size="14" name="File">'

FileList.insertAdjacentHTML("beforeEnd","<br>")

FileList.insertAdjacentHTML("beforeEnd",str)

}

}

</script>

</HEAD>

<body MS_POSITIONING="GridLayout">

<form id="Form1" method="post" encType="multipart/form-data" runat="server">

<FONT face="宋体">

<TABLE id="Table1" style="BORDER-RIGHT: #33cc66 2px grooveBORDER-TOP: #33cc66 2px grooveZ-INDEX: 101LEFT: 136pxBORDER-LEFT: #33cc66 2px grooveBORDER-BOTTOM: #33cc66 2px groovePOSITION: absoluteTOP: 32px"

width="500" align="center">

<TBODY>

<TR height="20">

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="34%"> </TD>

</TR>

<TR>

<TD colSpan="2"> </TD>

<TD colSpan="4"><FONT class="WelcomeText" face="幼圆" color="#ff00ff" size="4">      添加新地图</FONT></TD>

</TR>

<tr>

<td class="TagTitle" align="right" colSpan="3"><b>请选择地图规格: </b></td>

<td class="TagTitle" colSpan="2"><input id="rows" style="WIDTH: 32pxHEIGHT: 22px" type="text" size="1" value="1" runat="server"

NAME="rows">行<input id="cols" style="WIDTH: 32pxHEIGHT: 22px" type="text" size="1" value="1" runat="server"

NAME="cols">列</td>

<td colSpan="2">  <input style="WIDTH: 72pxHEIGHT: 22px" onclick="AddFile()" type="button" value="确定"></td>

</tr>

<TR>

<TD class="TagTitle" align="right" width="33%" colSpan="3"><B>请选择地图文件:</B> 

</TD>

<TD class="TagTitle" width="33%" colSpan="4"></TD>

</TR>

<tr>

<td colSpan="7">

<p id="MyFile"><font class="TagTitle"><b>          第1个地图:</b></font>

<input style="WIDTH: 200pxHEIGHT: 22px" type="file" size="14" name="File">

</p>

</td>

<TR>

<TD class="TagTitle" align="right" width="33%" colSpan="3"><B>请输入地图存储名称:</B> 

</TD>

<TD class="TagTitle" align="left" width="33%" colSpan="4"><INPUT id="MapName" style="WIDTH: 128pxHEIGHT: 22px" type="text" size="16" name="Password"

runat="server">

<asp:requiredfieldvalidator id="RequiredFieldValidator2" runat="server" CssClass="TagTitle" ErrorMessage="地图名不能为空"

Font-Names="微软雅黑" Font-Size="X-Small" ControlToValidate="MapName"></asp:requiredfieldvalidator></TD>

</TR>

<TR>

<TD class="TagTitle" style="HEIGHT: 29px" align="right" width="33%" colSpan="3"><B><asp:label id="Msg0" runat="server"></asp:label> </B>

</TD>

<TD class="TagTitle" style="HEIGHT: 29px" width="33%" colSpan="4"><span class="ErrorMessage" id="OutputSpan" runat="server"><asp:label id="Msg" runat="server"></asp:label></span></TD>

</TR>

<TR>

<TD width="11%"> </TD>

<TD width="11%"> </TD>

<TD width="22%" colSpan="4">      

<asp:button id="SubmitButton" runat="server" Font-Names="微软雅黑" Font-Size="X-Small" Text="提交"

Height="26px" Width="60px"></asp:button> <INPUT id="CancelButton" style="FONT-SIZE: x-smallWIDTH: 60pxFONT-FAMILY: 微软雅黑HEIGHT: 26px"

type="reset" value="清除" name="CancelButton"></TD>

<TD width="34%"> 

</TD>

</TR>

</TBODY>

</TABLE>

<TABLE id="Table2" style="Z-INDEX: 102LEFT: 136pxWIDTH: 491pxPOSITION: absoluteTOP: 8pxHEIGHT: 26px"

width="491" align="center">

<TR>

<TD class="TagTitle"><A href="DeleteMap.aspx"><FONT class="WelcomeText" face="幼圆">删除已有地图</FONT></A></TD>

</TR>

</TABLE>

</FONT>

</form>

</TR></TBODY></TABLE></FONT>

</body>

</HTML>

2)后台cs文件:关键是使用Request.Files获取刚上传的文件:

using System

using System.Collections

using System.ComponentModel

using System.Data

using System.Drawing

using System.Web

using System.Web.SessionState

using System.Web.UI

using System.Web.UI.WebControls

using System.Web.UI.HtmlControls

using System.Configuration

namespace ZiFengLast.SystemSet

{

/// <summary>

/// MapAdmin 的摘要说明。

/// </summary>

public class AddMap : System.Web.UI.Page

{

protected System.Web.UI.WebControls.Button SubmitButton

protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator2

protected System.Web.UI.HtmlControls.HtmlGenericControl OutputSpan

protected System.Web.UI.WebControls.Label Msg

protected System.Web.UI.WebControls.Label Msg0

protected System.Data.SqlClient.SqlConnection MapConn

protected System.Data.SqlClient.SqlCommand MapComm

protected System.Web.UI.HtmlControls.HtmlInputText rows

protected System.Web.UI.HtmlControls.HtmlInputText cols

protected System.Web.UI.HtmlControls.HtmlInputText MapName

private void Page_Load(object sender, System.EventArgs e)

{

// 在此处放置用户代码以初始化页面

}

#region Web 窗体设计器生成的代码

override protected void OnInit(EventArgs e)

{

//

// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。

//

InitializeComponent()

base.OnInit(e)

}

/// <summary>

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。

/// </summary>

private void InitializeComponent()

{

this.MapConn = new System.Data.SqlClient.SqlConnection()

this.MapComm = new System.Data.SqlClient.SqlCommand()

this.SubmitButton.Click += new System.EventHandler(this.SubmitButton_Click)

//

// MapConn

//

this.MapConn.ConnectionString =System.Configuration.ConfigurationSettings.AppSettings["sqlMap"]

//

// MapComm

//

this.MapComm.Connection = this.MapConn

this.Load += new System.EventHandler(this.Page_Load)

}

#endregion

private void SubmitButton_Click(object sender, System.EventArgs e)

{

try

{

HttpFileCollection file=Request.Files

System.Text.StringBuilder FileNameArray=new System.Text.StringBuilder()

string SaveName=this.MapName.Value.Trim()

string FileExtension0=System.IO.Path.GetExtension(System.IO.Path.GetFileName(file[0].FileName))

for(int i=0i<file.Counti++)

{

HttpPostedFile PostFile=file[i]

string FileName=System.IO.Path.GetFileName(PostFile.FileName)

FileName.Replace("","_")

string FileExtension=System.IO.Path.GetExtension(FileName)

string ContentType=PostFile.ContentType.ToString()

string LastSaveName=SaveName+(i+1).ToString()+FileExtension

PostFile.SaveAs(Request.MapPath("../Map/"+LastSaveName))

FileNameArray.Append(LastSaveName)

FileNameArray.Append("")

}

this.MapComm.CommandText="Select [Map].* from [Map] where MapName='"+SaveName+"'"

this.MapConn.Open()

System.Data.SqlClient.SqlDataReader rd=this.MapComm.ExecuteReader()

if(rd.Read())

{

this.MapConn.Close()

this.MapConn.Dispose()

this.MapComm.Dispose()

rd.Close()

Msg0.Text="<font class=ErrorMessage>上传文件失败!</font>"

Msg.Text="<font class=ErrorMessage>已有该地图名称,请指定另外的名称</font>"

}

else

{

rd.Close()

this.MapComm.CommandText="insert into [Map](MapName,MapRows,MapCols,MapFileNames) Values('"+SaveName+"',"+int.Parse(rows.Value)+","+int.Parse(cols.Value)+",'"+FileNameArray+"')"

//Response.Write(MapComm.CommandText)

this.MapComm.ExecuteNonQuery()

this.MapConn.Close()

this.MapConn.Dispose()

this.MapComm.Dispose()

}

Msg0.Text="<font class=ErrorMessage>上传文件成功!</font>"

Msg.Text="<font class=ErrorMessage>共计上传文件"+file.Count.ToString()+"个"+"<br>"+FileNameArray+"</font>"

}

catch(Exception ee)

{

Msg0.Text="<font class=ErrorMessage>上传文件失败!</font>"

Msg.Text="<font class=ErrorMessage>"+ee.ToString()+"</font>"

}

}

}

}

要一模一样的看jqgird的editGridRow function,分开的是在grid.formedit.js 这个js里面

要对话框中生成form的可以看jquery ui demo中dialog文件夹下modal-form.html