My Web道

WEB制作科 受講記録 …とその後も続くWEB制作に関する活動・学習記録です。

※ 当サイトはアフィリエイト広告を利用しています

【WordPress】カスタムフィールド活用術:記事ごとにCSSを設定する

CSS

個別の記事にCSSを設定する

カスタムフィールドを活用すると、作成中の記事に独自のスタイルを設定することができます。


WordPressの記事単体に独自のスタイルを設定したい場合、
エディタ内でCSSを書いてもスタイルを設定することはできますが、
これは推奨できる方法ではありません。

なので、ここではカスタムフィールドを活用したCSS設定方法をシェアしますね。

手順

1. カスタムフィールドを作成

1.1. 投稿の編集画面から、カスタムフィールドを作成します。
  カスタムフィールド追加欄が表示されていない場合は、投稿画面上部、「表示オプション」から、カスタムフィールドにチェックがない可能性があります。未チェックなら、チェックを入れ、表示させます。



1.2. カスタムフィールドを作成します。
  ※フィールド名は任意です。ここでは、「custom_CSS」で作成します。

  



2. functions.php の編集

 ※functions.php 編集前には念のためバックアップを取りましょう。


2.1. functions.php に2.2.以下のコードを追記します。

  ただし、ここでは functions.php の今後の管理を考慮し、別のファイルを新規作成し、以下を記述することにします。
  こうして外部ファイル化すると、functions.php があまりごちゃごちゃせず、シンプルかつ効率的です。
  また、functions.php自体は極力編集しないで済むので、functions.phpファイル破損のリスクが避けられます。


2.2. ここでは、widgets.phpというファイルを新規作成し、下記コードを記述することにします。
  また、functions.phpからの外部参照を一箇所にまとめたいので、「lib」フォルダを新規作成し、そのフォルダ内にwidgets.phpファイルを配置します。

《widgets.php  

<?php
/*
 * Custom CSS Widget
 */
function custom_css_hooks() {
    add_meta_box('custom_css', 'Custom CSS', 'custom_css_input', 'post', 'normal', 'high');
    add_meta_box('custom_css', 'Custom 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();
    }
}
add_action('admin_menu', 'custom_css_hooks');
add_action('save_post', 'save_custom_css');
add_action('wp_head','insert_custom_css');
?>


2.3. functions.php には、上記コード参照用に以下コードを追記します。

《functions.php  

/*widgets.php を読み込み*/
require_once locate_template('lib/widgets.php');     // サイドバー、ウィジェットの関数


以上で、「Custom CSS」ウイジェットが追加され、custom_CSSフィールドに個別記事ページごとのCSSを設定することができるようになりました。
あとは、該当の記事編集画面を開き、custom_CSSフィールドの値欄にCSSを記述すればOKです。


【参考サイト】
Custom CSS Per Post | Digging Into WordPress :
https://digwp.com/2010/02/custom-css-per-post/

※ 当サイトはアフィリエイト広告を利用しています