記事毎に専用のCSSを追加できるようになるWordPressプラグイン「add-css-to-post」

記事毎に専用のCSSを追加できるようになるWordPressプラグイン「add-css-to-post」

記事毎に専用のCSSを追加できるようになるWordPressプラグイン「add-css-to-post」

特定の記事だけで使いたい CSS をいちいちテーマのスタイルシートに追加するのって面倒ですよね。わざわざテーマファイルに追記しなくても、記事投稿画面でその記事だけに CSS を適用するためのプラグイン「add-css-to-post」を紹介したいと思います。

もともとは functions.php にコードを追加することで、記事編集ページに CSS 追加用のボックスを表示する方法が かちびと.net さんで紹介されてました。コードは以下の通り。


add_action('admin_menu', 'custom_css_hooks');
add_action('save_post', 'save_custom_css');
add_action('wp_head','insert_custom_css');

function custom_css_hooks() {
add_meta_box('custom_css', '追加するCSS', 'custom_css_input', 'post', 'normal', 'high');
add_meta_box('custom_css', '追加するCSS', 'custom_css_input', 'page', 'normal', 'high');
}

function custom_css_input() {
global $post;
echo '<input type="hidden" name="custom_css_noncename" id="custom_css_noncename" value="'.wp_create_nonce('custom-css').'" />';
echo '<textarea name="custom_css" id="custom_css" rows="5" cols="30" style="width:100%;">'.get_post_meta($post->ID,'_custom_css',true).'</textarea>';
}

function save_custom_css($post_id) {
if (!wp_verify_nonce($_POST['custom_css_noncename'], 'custom-css')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$custom_css = $_POST['custom_css'];
update_post_meta($post_id, '_custom_css', $custom_css);
}

function insert_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(), '_custom_css', true).'</style>';

endwhile; endif;
rewind_posts();
}

}

このコードを利用しているテーマの functions.php に追加してもいいんですが、プラグイン化してくれているので非常に簡単に導入することができます。

スポンサードリンク

add-css-to-postのインストール

1. かちびと.netにアクセスします。
2. 記事の下の方にある ZIP ファイルをダウンロードします。

add-css-to-postのダウンロード

3. ダウンロードしたファイルを展開し wp-content/plugins にアップロードします。
4. 管理画面の [プラグイン] ページで、add-css-to-post プラグインを有効化します。

add-css-to-postの使い方

プラグインを有効化したら、記事の編集画面に以下のようなボックスが現れます。

add-css-to-postの編集ボックス

もし表示されていないという場合は、表示オプションから「add CSS」にチェックを入れてください。

add CSS

あとは、add CSS のボックスに追加したい CSS を記述するだけです。

あとがき

スタイルシートに追加するほどでもないけど・・・という時に便利ですね。プラグイン化までしてくれていてほんとありがたいです。

この記事が気に入ったら
いいね!してね♪

Twitter で
スポンサードリンク

関連記事

One thought on “記事毎に専用のCSSを追加できるようになるWordPressプラグイン「add-css-to-post」

  1. Pingback: 画像のマウスオーバー時にアクションをつけました。 | chomerukin.jp

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です