LoginSignup
3
4

More than 5 years have passed since last update.

【Wordpress】増えてしまったタグやカテゴリーのテンプレートをフォルダ毎に整理する方法

Posted at

はじめに

WordPressでサイト構築をしていると、カテゴリーやタグのテンプレートファイルが増えてしまうことって、ないでしょうか?
今回は増えてしまったテンプレートファイルをフォルダ毎に整理する方法をまとめました。

実装方法

1.テンプレートファイルをそれぞれフォルダに移動します。
(タグテンプレートならtag,カテゴリーならcategoryといったところでしょうか。)
2.functions.phpにスラッグ毎にテンプレートを切り替える処理を加えます。

サンプルコード

まずは、テンプレートファイルを下記のフォルダ階層の様に移動させていきます。

フォルダ階層イメージ
wordpress/
 ├ wp-content/
 │ └ themes/
 │   └ your-theme/
 │     └ tag/
 │       └ tag-{slug}.php
 │     └ category/
 │       └ category-{slug}.php
 │     └ functions.php

続いて、functions.phpに処理を追加します。

functions.php
/**
 * タグテンプレート
 */
add_filter('tag_template', function($template){
  $tag = get_queried_object();
  //専用テンプレートが用意されているのか判定
  $alternative_template = locate_template( "tag/tag-{$tag->slug}.php" );

  // 専用テンプレートが用意されている場合
  if ($alternative_template) {
    return $template = $alternative_template;
  }
  // 専用テンプレートが用意されていない場合
  return $template;
});

/**
 * カテゴリテンプレート
 */
add_filter('category_template', function($template){
  $category = get_queried_object();
  //専用テンプレートが用意されているのか判定
  $alternative_template = locate_template( "category/category-{$category->slug}.php" );

  // 専用テンプレートが用意されている場合
  if ($alternative_template) {
    return $template = $alternative_template;
  }
  // 専用テンプレートが用意されていない場合
  return $template;
});

これでテンプレートファイルが綺麗に整理されたと思います。
同じ要領で、コメントや著者テンプレートも整理することができますので、よかったら試してみてください。

参考サイト

WordPress codex プラグイン API/フィルターフック一覧
http://ur2.link/L3ES

WordPress codex 関数リファレンス/get queried object
http://ur2.link/L3EX

皆様のお役に立てれば幸いです。

3
4
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
3
4