在写Goodbye, TWENTY TWELVE这篇日志时,我希望针对此日志设计独立于主题的样式,而且日志也涉及到调用highcharts framework。既然是专门针对某一日志/页面的CSS/JS,自然不想采取全局添加的方式,这样即耗费资源,也增加了不必要的载入时间。因此,通过WP主题的functions.php写段小小的hack是最优的方法。

思路

WordPress内置Custom Fields用于添加额外的字段。我设置了custom-csscustom-js两个Custom Fields用于添加独立的CSS和JS地址。然后通过主题文件下的functions.php检查日志是否有独立的CSS/JS需要调用。

实现方法

1、添加以下代码段到functions.php文件中。

function custom_post_styles() {
	if (!is_single()) return;
	global $post;
	$customCSS = get_post_meta($post->ID, 'custom-css', false);
	if (empty($customCSS)) return;
	$styleNum = 1;
	foreach ($customCSS as $CSS) {
		$styleID = 'post-style' . $styleNum;
		wp_register_style(
			$styleID,
			$CSS,
			false,
			null,
			'all'
		);
		wp_enqueue_style($styleID);
		$styleNum++;
	}
}

function custom_post_scripts() {
	if (!is_single()) return;
	global $post;
	$customJS = get_post_meta($post->ID, 'custom-js', false);
	if (empty($customJS)) return;
	$scriptNum = 1;
	foreach ($customJS as $JS) {
		$scriptID = 'post-script' . $scriptNum;
		wp_enqueue_script(
			$scriptID,
			$JS,
			false,
			null,
			true
		);
		$scriptNum++;
	}
}

add_action('wp_enqueue_scripts', 'custom_post_scripts');
add_action('wp_enqueue_scripts', 'custom_post_styles');

2、然后在日志编辑器下面的Custom Fields里新建custom-csscustom-js两个自定义内容就行了,value栏里填CSS/JS的调用地址,若有多个CSS/JS只需格外增加一栏custom-css或者custom-js就行了。

custom

就这么简单,没了。

4 Reponses So Far ↓

  1. g.zhen.ning:

    现在没邮件通知了,可考虑添加上。

  2. iPUNKID:

    我以为这个功能都没人用了,已添加。

  3. yang:

    这个主题是你自己写的吗?

Leave a Reply ↓