LoginSignup
0
0

More than 5 years have passed since last update.

【Wordpress】記事ごとにテーマフォルダ内のCSSやJavaScriptなどを読み込む方法

Posted at

大まかな流れ

  1. 記事内の<head>内、及びに</body>直前に、カスタムフィールドに書いたCSSやScriptを挿入出来るようにする。
  2. カスタムフィールド内のショートコードでテーマフォルダ内のファイルを読み込む。

前段階

header.php
//~~~
wp_head();
//~~~
if (is_single()||is_page()): //記事ページor固定ページの場合
  echo apply_filters('the_content', get_post_meta($post->ID, 'foo', true));
endif;

投稿時にカスタムフィールド「foo」の値に直接CSSを書けば読み込んでくれる。
<style>で囲むことを忘れずに。

footer.php
//~~~
wp_footer();
//~~~
if (is_single()||is_page()): //記事ページor固定ページの場合
  echo apply_filters('the_content',get_post_meta($post->ID,'bar',true));
endif;

投稿時にカスタムフィールド「bar」の値に直接scriptを書けば読み込んでくれる。
<script>で囲むことを忘れずに。

テーマフォルダ内のファイルを読み込む(本題)

最初に試した方法(間違い)

functions.php
function show_path_to(){
  return get_template_directory_uri(); //親テーマディレクトリ
  //return get_stylesheet_directory_uri(); //子テーマディレクトリ
}
add_shortcode('path', 'show_path_to');
カスタムフィールド「foo」
<link rel="stylesheet" href="[path]/css/bar.css">

ショートコードが動かずにそのまま表示された。当然ファイルは読み込めていない。

敗因

HTMLタグ内でのショートコード使用には制限があるらしい。
imgのsrc属性内等なら動く。

上手くいった方法

functions.php
function includeFile($args){
  $template = get_template_directory_uri();
  //$template = get_stylesheet_directory_uri(); 子テーマを使っている場合はこちら
  switch($args['kind']){
    case 'js':
      return '<script src="'.$template.'/js/'.$args['name'].'"></script>';
      break;
    case 'css':
      return '<link rel="stylesheet" href="'.$template.'/css/'.$args['name'].'">';
      break;
    default:
      return;
      break;
  }
}
add_shortcode('file', 'includeFile');
カスタムフィールド「foo」
[file kind=css name=foobar.css]
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0