WordPress 让特定的文章使用特定的CSS样式

6 篇文章 0 订阅

WP大学之前有一篇文章介绍的是采用特定php模板的方式(见:WordPress不同分类使用不同的文章模板),本文要介绍的是自定义css的方式。

今天有个人问这个问题:怎么为Wordpress的特定文章添加特定的css样式,这篇文章将会回答一下。

大致的“原理”:以post meta的方式在文章的发布/编辑页面添加自定义输入栏用以输入自定义的css,在文章详情页载入前述输入的css。

WORDPRESS自定义CSS:最简单的方式

这种方式的优点是载入的代码很少,考虑性能和安全性的话,可以考虑这种方式:

/*
为特定文章添加特定css最简单的方式.
*/
/*添加自定义CSS的meta box*/
add_action('admin_menu', 'cwp_add_my_custom_css_meta_box');
/*保存自定义CSS的内容*/
add_action('save_post', 'cwp_save_my_custom_css');
/*将自定义CSS添加到特定文章(适用于Wordpress中文章、页面、自定义文章类型等)的头部*/
add_action('wp_head','cwp_insert_my_custom_css');
function cwp_add_my_custom_css_meta_box() {
	add_meta_box('my_custom_css', '自定义CSS', 'cwp_output_my_custom_css_input_fields', 'post', 'normal', 'high');
	add_meta_box('my_custom_css', '自定义CSS', 'cwp_output_my_custom_css_input_fields', 'page', 'normal', 'high');
}
function cwp_output_my_custom_css_input_fields() {
	global $post;
	echo '<input type="hidden" name="my_custom_css_noncename" id="my_custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
	echo '<textarea name="my_custom_css" id="my_custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_my_custom_css',true).'</textarea>';
}
function cwp_save_my_custom_css($post_id) {
	if (!wp_verify_nonce($_POST['my_custom_css_noncename'], 'custom-css')) return $post_id;
	if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
	$my_custom_css = $_POST['my_custom_css'];
	update_post_meta($post_id, '_my_custom_css', $my_custom_css);
}
function cwp_insert_my_custom_css() {
	if (is_page() || is_single()) {
		if (have_posts()) : while (have_posts()) : the_post();
		echo '<style type="text/css">'.get_post_meta(get_the_ID(), '_my_custom_css', true).'</style>';
		endwhile; endif;
		rewind_posts();
	}
}

这种方式的缺点是,界面看起来很一般.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值