WordPressのオリジナルテーマを作ってみる

2023.05.05 08:00
2023.05.05 09:28
WordPressのオリジナルテーマを作ってみる

1. テーマ用のディレクトリとファイルを作成

WPのオリジナルテーマを作ってみたいと思います。具体的にはWP内の所定のディレクトリにテーマ用のディレクトリをつくってそこに必要なファイルを入れていくようですね。

1-1. ディレクトリ構成

大まかにはこんな感じです。作りによっては必要ないものあるっぽいですね。

/wp-content/themes/テーマ名(英数字のみ)
|- /img/(画像を入れるフォルダ)
|- /templates/(共通パーツを入れるフォルダ)
|- 404.php(エラー画面が必要な場合)
|- archive.php(必須:投稿一覧)
|- category.php(カテゴリ一覧が必要な場合)
|- footer.php(必須)
|- functions.php(必須)
|- header.php(必須)
|- index.php(必須)
|- page.php(固定ページ)
|- screenshot.png
|- sidebar.php(サイドバーが必要な場合)
|- single.php(必須:投稿詳細ページ)
|- style.css(必須)
|- tag.php(タグ一覧が必要な場合)

1-2. テーマ名と画像を指定

style.cssに書いたメタ情報と、screenshop.pngがWP上で表示されるようです。
screenshopt.pngのサイズは「1200×900」のようです。

@chartset "UTF-8";
/*!
Theme Name: テーマ名
Author: 作った人
Author URI: 作った人のサイトURL
Description: 概要があれば

Version: 1.0
*/

この下にテーマのcssを書いていく

1-3. functions.phpの変更

<?php
/**
 * Functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package WordPress
 * @subpackage テーマ名を半角英数字で
 */


// author情報からユーザー名の特定防止
function disable_author_archive_query() {
  if( preg_match('/author=([0-9]*)/i', $_SERVER['QUERY_STRING']) ){
    wp_redirect( home_url() );
    exit;
  }
}
add_action('init', 'disable_author_archive_query');

// WordPress REST API によるユーザー情報特定防止
function my_filter_rest_endpoints( $endpoints ) {
  if ( isset( $endpoints['/wp/v2/users'] ) ) {
    unset( $endpoints['/wp/v2/users'] );
  }
  if ( isset( $endpoints['/wp/v2/users/(?P<id>[\\d]+)'] ) ) {
    unset( $endpoints['/wp/v2/users/(?P<id>[\\d]+)'] );
  }
  return $endpoints;
  }
add_filter( 'rest_endpoints', 'my_filter_rest_endpoints', 10, 1 );

// WordPressのバージョン情報削除
function remove_src_wp_ver( $dep ) {
	$dep->default_version = '';
}
add_action( 'wp_default_scripts', 'remove_src_wp_ver' );
add_action( 'wp_default_styles', 'remove_src_wp_ver' );

2. レイアウトファイルを作る

実際にレイアウトとなるファイルがパーツごとにあるようなので、作り込んでいきます。
header.phpとfooter.php、index.phpが必須のようですね。404.phpを作ると、エラー画面もカスタマイズできるようです。

2-1. header.phpの設定

<?php
/**
 * The header.
 *
 * This is the template that displays all of the <head> section and everything up until main.
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package WordPress
 * @subpackage テーマ名を半角英数字で
 */

?>
<!doctype html>
<html <?php language_attributes(); ?>>
<head>
  <meta charset="<?php bloginfo( 'charset' ); ?>" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <?php wp_head(); ?>
</head>

<body <?php body_class(); ?>>

1-4. footer.phpの設定

<?php
/**
 * The template for displaying the footer
 *
 * Contains the closing of the #content div and all content after.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package WordPress
 * @subpackage テーマ名を半角英数字で
 */

?>

<?php wp_footer();?>

</body>
</html>

1-4. 404.phpの設定

<?php
/**
 * The template 
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package WordPress
 * @subpackage テーマ名を半角英数字で
 */

get_header();

get_footer();

1-4. index.phpの設定

<?php
/**
 * The template 
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package WordPress
 * @subpackage テーマ名を半角英数字で
 */

get_header();

get_footer();

1-5. 共通ファイルの作成

templatesの中に入れて使えるみたいです。例えばこんな感じでしょうか。

  • content-category.php
  • content-neighborhood.php
  • content-none.php
  • content-page.php
  • content-pagination.php
  • content-search.php
  • content-thumbnail.php
  • content-contents.php
  • contents.php

1-6. テーマファイルの中でよく使う変数と関数

パスの指定など、テーマ内で使う関数などがあるようです。

<?php echo home_url('/');?>

サイトのパスを取得できるようです。リンクなどで使えますね。

<?php echo get_template_directory_uri(); ?>

テーマのディレクトリパスを取得できるようです。テーマに入っているcssや画像などのパスで使えますね。

3. アーカイブの設定

記事投稿の一覧や詳細のことをアーカイブページ、詳細ページへのリンクをパーマリンクと呼ぶらしいです。それを作っていきます。

必要なのは以下のファイル

  • archive.php(一覧)
  • single.php(詳細)

3-1. functions.phpに対応コードを書き込む

アーカイブを反映させるのに、functions.phpにコードを追加させる必要があるようです。

// 投稿のアーカイブページを作成する
function post_has_archive($args, $post_type)
{
    if ('post' == $post_type) {
        $args['rewrite'] = true; // リライトを有効にする
        $args['has_archive'] = 'news'; // 任意のスラッグ名
    }
    return $args;
}
add_filter('register_post_type_args', 'post_has_archive', 10, 2);

archive.php

    <?php if (have_posts()):?>
    <div class="mt-8 py-4 rounded-xl lg:max-w-2xl lg:mx-auto lg:max-w-4xl">
      <?php while (have_posts()) : the_post();?>
      <div class="mb-6 py-2 border-b border-gray-200">
        <p class="py-1">
          2023.12.12
        </p>
        <div class="text-sm leading-relaxed md:text-base md:leading-relaxed">
          <a href="<?php the_permalink(); ?>" class="text-origin-700 hover:underline"><?php the_title(); ?></a>
        </div>
      </div>
      <?php endwhile;?>
    </div>
    <?php endif; ?>

single.php

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>

    <?php // タイトルを表示する start ?>
    <h1 class="blog-detail__title"><?php the_title(); ?></h1>
    <?php // タイトルを表示する end ?>

    <?php // アイキャッチ画像を表示する start ?>
    <?php if(has_post_thumbnail()): ?>
    <div class="blog-detail__image">
        <img src="<?php the_post_thumbnail_url('large'); ?>">
    </div>
    <?php endif; ?>
    <?php // アイキャッチ画像を表示する end ?>

    <?php // 本文を表示する start ?>
    <div class="blog-detail__body">
        <div class="blog-content"><?php echo the_content(); ?></div>
    </div>
    <?php // 本文を表示する end ?>

<?php endwhile; endif; ?>

トップなどに最新投稿を表示させる場合はこんな感じ。

<ul>
<?php
$args = array(
'posts_per_page' => 5 // 表示件数
);
$posts = get_posts( $args );
foreach ( $posts as $post ): // ループの開始
setup_postdata( $post ); // 記事データの取得
?>
<li>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php
endforeach; // ループの終了
?>
</ul>

ひとまずここまでである程度表示されました。

今回は以上です!