Warning: Undefined array key "css" in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 7

Warning: Trying to access array offset on value of type null in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 7

Warning: Undefined array key "jssrc" in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 8

Warning: Trying to access array offset on value of type null in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 8

Warning: Undefined array key "js" in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 9

Warning: Trying to access array offset on value of type null in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 9

Warning: Undefined variable $tn_js in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/header-single.php on line 59
特定のページにだけ css や javascript を投稿画面から適用する方法、ついでにmeta descriptionも – どっといこ
WordPress  
  特定のページにだけ css や javascript を投稿画面から適用する方法、ついでにmeta descriptionも
2018
11
Aug

特定のページにだけ css や javascript を投稿画面から適用する方法、ついでにmeta descriptionも

最終更新日: 2020年11月10日

このサイトのように投稿ページで色々なことを試すようなサイトでは、そのページでしか使わないスタイルやjavascriptが必要になります。ですが、サイト全体に適用するcssやjsファイルにコードを追加するのはコード量が増えて効率が悪い気がします。特定の投稿ページだけに適用するスタイルやjavascriptがあれば便利だと思います。

ついでに meta description も投稿ページごとに設定できるようにします。

css javascript を、特定のページだけに適用する方法

 

テキストエディタに書き込めば済む話でしょ?その通りなのですが、私は前述のカスタムフィールドをつかって css は header に javascript は fooeter に書き込んでいます。
javascriptについてだけ言うならば管理者権限で投稿しなければ、テキストエディタからは投稿できないです。

header.php


$custom_fields = get_post_custom();  //カスタムフィールドの値をまとめて取得します
$desc = $custom_fields['desc'][0];   //投稿ページ用のdescription
$tn_css = $custom_fields['css'][0];  //追加するcss
$jssrc = $custom_fields['jssrc'][0]; //読み込むjsファイル用
$tn_js = $custom_fields['js'][0];    //追加するjs



/*それぞれ適当な場所へ記述します。入力値をエスケープする場合は追加処理してください。*/
if( $desc ){ echo '<meta name="description" content="'.$desc.'">'; }
if( $tn_css ){ echo '<style>'.$tn_css.'</style>'; }
if( $jssrc ){ echo '<script src="'.$jssrc.'"></script>'; }
if( $tn_js ){ echo '<script>'.$js.'</script>'; }

/*javascriptのappendをつかえば実際には、
カスタムフィールド一つで済むかもしれませんが分かり易いようにこうしています。*/

プラグインなしで投稿ページにカスタムフィールドを複数作成する記事を書きました。

 

top


Warning: Undefined array key "jssrc" in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/footer-single.php on line 30

Warning: Trying to access array offset on value of type null in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/footer-single.php on line 30

Warning: Undefined array key "js" in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/footer-single.php on line 31

Warning: Trying to access array offset on value of type null in /home/dotequal/pub/ja-ja.jp/wp-content/themes/ja-ja/footer-single.php on line 31