WordPress自作テーマ制作⑧│見た目(style.css)の作成

WordPressの自作テーマ第8弾!

基本的なテンプレートが揃ってきたので、今回はようやくCSSを書いて見た目を整えます。

厳密の言うと、最低限のベース(自前のスターターテーマ)の見た目を整えていきます。

目次

著者

WEB制作をしているデジタルノマド
WordPressのカスタマイズが好きで、色々と自作しています。

WordPressのカスタマイズに困ったらご相談ください!

CSSの命名規則

CSSの命名規則は色々、流派があると思います。

今回は最小限のコードかつ上書きしやすいという条件のルールにしました。

idは指定しない

idは#を付けることでCSSで指定することができますが、こちらはJavascriptの指定だけに使うようにします。

CSSを書くときにclassよりもidよりの方が優先されるというルールがあるのですが、

上書きできる余地を残して置きたいという理由もあります。

あとは単純にclassだけを使うというルールもシンプルで良いかなと思います。

リセットCSSを使わない

すべてのブラウザのCSSを統一するリセットCSS

データが重いそうなので、いったん使わない方向で考えています。

WordPressで用意されているCSSを使わない

読み込みを全て停止しているのでブロックエディタ等で読み込まれるCSSも使わない方向にしています。

デメリットはすべてのブロック全てのCSSを手入力しないといけなくなります。

CSSの挿入

CSSで最低限の見た目を整えます。

今回はモバイルファーストのサイト(最大幅600px)を想定して、見た目を整えました。

PCとモバイルの見た目が一緒ということでコード量はもちろん、記事を書くときもそのままの見た目でOKなのがメリットです。

style.cssの読み込む場合

header.phpのhead部分に下記のコードを挿入します。

style.cssの後に現在の時間を入れる事で、CSSを更新しても即座に更新されるようになります。

テーマの開発中はこちらの方が使い勝手が良いです。

<link rel="stylesheet" type="text/css" href="<?php bloginfo('template_url') ?>/style.css?<?php echo date('YmdHis'); ?>">

style.cssの読み込む場合

通常のfunctions.phpからstyle.cssを読み込む方法も書いておきます。

下記のコードをfunctions.phpに挿入します。

こちらの場合はブラウザキャッシュが効いてしまうので、CSSのちょっとした変更が反映されない場合があります。

その場合はキャッシュのクリアをしましょう。

// style.cssの読み込み
function enqueue_styles() {
    wp_enqueue_style('main-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'enqueue_styles');

style.cssに追記

style.cssに下記のコードを追記します。

書いていて気が付いたのですが、WordPress側のCSSを一切読み込まないようにしているので、

ブロック周りも自分で書かない(カラムとか文字位置とか)といけないようです。

最小限のサイトを作るのはそれなりに手間です。

/*
    Theme Name: SUIMIN
    Theme URI: https://suimin-theme.com/
    Author: MOTOKI LLC.
    Author URI: https://motoki-design.co.jp/wordpress/
    Description: SEO-optimised starter theme in line with Google's standards.
    Tags: blog, block-styles
    Version: 1.0.0
    Requires at least: 5.6
    Tested up to: 5.6
    Requires PHP: 7.3.0
    License: GNU General Public License v2 or later
    License URI: http://www.gnu.org/licenses/gpl-2.0.html
    Text Domain: suimin
    Domain Path: /languages
*/

/*---------------------------------

  共通パーツ

---------------------------------*/
/* ベース */
body{
	font-family:"Yu Gothic Medium", "游ゴシック Medium", YuGothic, "游ゴシック体", "ヒラギノ角ゴ Pro W3", "メイリオ", sans-serif;
    background-color: #EFEFEF;
    max-width: 600px;
    padding-left: 1em;
    padding-right: 1em;
    margin: 0 auto;
}
/* リスト */
ol, ul {
    list-style: none;
  	padding: 0;
}
/* 画像 */
figure {
    margin: 0;
}
img {
    border-style: none;
    height: auto;
    max-width: 100%;
}
/* リンク選択 */
a {
    color: #000;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
}
/* ウィジェット */
.is-layout-flex{
    display: flex;
    justify-content: center;
}
.wp-block-column {
    flex: 1;
    padding: 0 1em;
}
/* メニュー */
.global-menu-list,
.footer-menu-list {
    display: flex;
    justify-content: center;
}
.global-menu-list li{
    padding: 0 16px;
}
.global-menu-list li a,
.footer-menu-list li a {
    font-size: 14px;
}
/* 検索ボタン */
label.wp-block-search__label {
    display: none;
}
.wp-block-search__button {
    margin-left: 0.5em;
}
/*---------------------------------

  ヘッダー

---------------------------------*/
/* ヘッダー */
.site-title{
    text-align: center;
}
/*キャッチフレーズ*/
.catchphrase {
    font-size: 14px;
    font-weight: normal;
    position: relative;
    bottom: 8px;
}
.site-title > div {
    font-size: 0;
}
/* パンくず */
.breadcrumb {
    display: flex;
    font-size: 14px;
}
.breadcrumb li {
    align-items: center;
    display: inline-flex;
    position: relative;
}
.breadcrumb li:not(:last-child):after {
    background-color: currentColor;
    clip-path: polygon(45% 9%,75% 51%,45% 90%,30% 90%,60% 50%,30% 10%);
    content: "";
    height: 10px;
    margin: 0 8px;
    width: 10px;
}
/*---------------------------------

  コンテンツ

---------------------------------*/
/* ベース */
.main-content {
    background: #fff;
    padding: 1.5em;
    border-radius: 4px; 
}
.wrap {
    margin: 0 auto 2em;
}
/*タイトル*/
h1 {
    margin: 0;
}
.title {
    margin: 1em 0 0 0;
}
/* アイキャッチ */
.eyecatch {
    margin: 2em 0;
}
/* 日づけ */
.date {
    font-size: 13px;
}
/* 公開日 */
.time {
    display: none;
}
/*---------------------------------

  フッター

---------------------------------*/
/* ベース */
.footer-container {
    padding-bottom: 1em;
    padding-top: 1em;
}
/* フッターメニュー */
.footer-menu-list li{
    padding: 0 16px
}
.footer-menu-list li a {
    font-size: 14px;
}
/* コピーライト */
.copyright{
    text-align: center;
    font-size: 12px;
}

確認

このような見た目になりました。

アイキャッチ画像もサイトの幅にあったサイズに変更しています。

ここまでのコードまとめ

classを追加したりと、いろいろ微調整しました。

header.php
<!doctype html>
<html <?php language_attributes(); ?>>

<head>
    <meta charset="utf-8">
    <meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, viewport-fit=cover">
    <?php wp_head(); ?>
</head>

<body>
    <div id="site-title" class="site-title">
        <?php
        $custom_logo_id = get_theme_mod('custom_logo');
        $logo = wp_get_attachment_image_src($custom_logo_id, 'full');
        $imagesize = getimagesize($logo[0]);
        if ($imagesize) {
            $image_width = $imagesize[0];
            $image_height = $imagesize[1];
        }
        if (has_custom_logo()) :
            if (is_front_page() || is_home()) :
                echo '<h1><a href="' . esc_url(home_url('/')) . '" title="' .  get_bloginfo('name') . '" rel="home"><img width="' . $image_width . '" height="' . $image_height . '" src="' . esc_url($logo[0]) . '" alt="' . get_bloginfo('name') . '"></a>';
                echo '<div class="catchphrase"><span class="site-title" style="display: none;">' .  get_bloginfo('name') . '</span> ' . get_bloginfo('description', 'display') . '</div></h1>';
            else :
                echo '<div><a href="' . esc_url(home_url('/')) . '" title="' . get_bloginfo('name') . '" rel="home"><img width="' . $image_width . '" height="' . $image_height . '" src="' . esc_url($logo[0]) . '" alt="' . get_bloginfo('name') . '"></a>';
                echo '<div class="catchphrase"><span class="site-title" style="display: none;">' .  get_bloginfo('name') . '</span> ' . get_bloginfo('description', 'display') . '</div></div>';
            endif;
        else :
            if (is_front_page() || is_home()) :
                echo '<h1><a href="' . esc_url(home_url('/')) . '" title="' . get_bloginfo('name') . '" rel="home">' . get_bloginfo('name') . '</a>';
                echo '<div class="catchphrase">' . get_bloginfo('description', 'display') . '</div></h1>';
            else :
                echo '<div><a href="' . esc_url(home_url('/')) . '" title="' . get_bloginfo('name') . '" rel="home">' . get_bloginfo('name') . '</a>';
                echo '<div class="catchphrase">' . get_bloginfo('description', 'display') . '</div></div>';
            endif;
        endif;
        ?>
    </div>
    <nav class=" global-menu-nav">
        <ul class="global-menu-list">
            <?php
            wp_nav_menu([
                'container' => '',
                'theme_location' => 'global_menu',
                'items_wrap'      => '%3$s',
                'link_before'     => '<span >',
                'link_after'      => '</span>',
            ]);
            ?>
        </ul>
    </nav>
    <div id="breadcrumb" class="breadcrumb">
        <?php breadcrumb(); ?>
    </div>
footer.php
<?php get_sidebar(); ?>

<?php if (is_active_sidebar('sidebar')) : ?>
    <div id="sidebar_widget">
        <?php dynamic_sidebar('sidebar'); ?>
    </div>
<?php endif; ?>
<footer id="footer">
    <div class="footer-container">
        <?php if (is_active_sidebar('footer')) : ?>
            <div id="footer_widget">
                <?php dynamic_sidebar('footer'); ?>
            </div>
        <?php endif; ?>
        <ul class="footer-menu-list">
            <?php
            wp_nav_menu([
                'container'       => '',
                'theme_location'  => 'footer_menu',
                'items_wrap'      => '%3$s',
                'link_before'     => '<span >',
                'link_after'      => '</span>',
            ]);
            ?>
        </ul>
        <div class="copyright">
            ©2023 <?php bloginfo('name'); ?>
        </div>
    </div>
</footer>
<?php wp_footer(); ?>
</body>

</html>
single.php
<?php get_header(); ?>
<div class="wrap">
    <main id="main-content" class="main-content">
        <?php
        if (have_posts()) :
            while (have_posts()) : the_post();
        ?>
                <h1 class="title"><?php the_title(); ?></h1>
                <div class="date">
                    <div class="time"><?php the_time('Y/m/d'); ?></div>
                    <div class="modify"><?php the_modified_date('Y/m/d'); ?>
                    </div>
                </div>
                <?php
                if (has_post_thumbnail()) {
                    echo '<figure class="eyecatch">' . get_the_post_thumbnail() . '</figure>';
                }
                ?>
                <div class="content">
                    <?php the_content(); ?>
                </div>
        <?php
            endwhile;
        endif;
        ?>
    </main>
</div>
<?php get_footer(); ?>
page.php
<?php get_header(); ?>
<div class="wrap">
    <main id="main-content" class="main-content">
        <?php
        if (have_posts()) :
            while (have_posts()) : the_post();
        ?>
                <h1 class="title"><?php the_title(); ?></h1>
                <?php
                if (has_post_thumbnail()) {
                    echo '<figure class="thumbnail">' . get_the_post_thumbnail() . '</figure>';
                }
                ?>
                <div class="content">
                    <?php the_content(); ?>
                </div>
        <?php
            endwhile;
        endif;
        ?>
    </main>
</div>
<?php get_footer(); ?>
achive.php
<?php get_header(); ?>
<div class="wrap">
    <main id="main-content" class="main-content">
        <?php
        add_filter('get_the_archive_title_prefix', function ($prefix) {
            $prefix = '';
            return $prefix;
        });
        $archve_title = get_the_archive_title();
        echo '<h1 class="title">' . $archve_title . '</h1>';
        if (have_posts()) :
            while (have_posts()) : the_post();
        ?>
                <a href="<?php the_permalink(); ?>">
                    <h2 class="title"><?php the_title(); ?></h2>
                    <div class="date">
                        <div class="modify"><?php the_time('Y/m/d'); ?></div>
                    </div>
                    <?php
                    if (has_post_thumbnail()) {
                        echo '<figure class="thumbnail">' . get_the_post_thumbnail() . '</figure>';
                    }
                    ?>
                </a>
        <?php
            endwhile;
            $pagination = get_the_posts_pagination(array(
                'prev_text' => 'Prev',
                'next_text' => 'Next'
            ));
            echo preg_replace('/<h2 class="screen-reader-text">[^<]*<\/h2>/ui', '', $pagination);
        endif;
        ?>
    </main>
</div>
<?php get_footer(); ?>
home.php
<?php get_header(); ?>
<div class="wrap">
    <main id="main-content" class="main-content">
        <?php
        if (have_posts()) :
            while (have_posts()) : the_post();
        ?>
                <a href="<?php the_permalink(); ?>">
                    <h2 class="title"><?php the_title(); ?></h2>
                    <div class="date">
                        <div class="modify"><?php the_time('Y/m/d'); ?></div>
                    </div>
                    <?php
                    if (has_post_thumbnail()) {
                        echo '<figure class="thumbnail">' . get_the_post_thumbnail() . '</figure>';
                    }
                    ?>
                </a>
        <?php
            endwhile;
            $pagination = get_the_posts_pagination(array(
                'prev_text' => 'Prev',
                'next_text' => 'Next'
            ));
            echo preg_replace('/<h2 class="screen-reader-text">[^<]*<\/h2>/ui', '', $pagination);
        endif;
        ?>
    </main>
</div>
<?php get_footer(); ?>
404.php
<?php get_header(); ?>
<main id="main_content" class="main-content">
    <h1 class="title">ページが見つかりませんでした。</h1>
    <div class="content">
        <p>お探しのページは移動または削除された可能性があります。</p>
        <p>以下より キーワード を入力して検索してみてください。</p>
        <?php get_search_form(); ?>
    </div>
</main>
<?php get_footer(); ?>
searchform.php
<form role="search" method="get" class="searchForm" action="<?php echo home_url('/'); ?>" role="search">
    <input type="text" value="" name="s" placeholder="検索">
    <button type="submit" value="search">
        <div>検索</div>
    </button>
</form>
search.php
<?php get_header(); ?>
<div class="wrap">
    <main id="main-content" class="main-content">
        <?php
        echo '<h1 class="title">' . esc_html($_GET['s']) . 'の検索結果:' . $wp_query->found_posts . '件</h1>';
        if (have_posts()) :
            if (!$_GET['s']) :
                echo '<p>検索キーワードが未入力です</p>';
            else :
                while (have_posts()) : the_post();
        ?>
                    <a href="<?php the_permalink(); ?>">
                        <h2 class="title"><?php the_title(); ?></h2>
                        <div class="date">
                            <div class="modify"><?php the_time('Y/m/d'); ?></div>
                        </div>
                        <?php
                        if (has_post_thumbnail()) {
                            echo '<figure class="thumbnail">' . get_the_post_thumbnail() . '</figure>';
                        }
                        ?>
                    </a>
        <?php
                endwhile;
                $pagination = get_the_posts_pagination(array(
                    'prev_text' => 'Prev',
                    'next_text' => 'Next'
                ));
                echo preg_replace('/<h2 class="screen-reader-text">[^<]*<\/h2>/ui', '', $pagination);
            endif;
        else :
            echo '<p>記事が見つかりませんでした。</p>';
        endif;
        ?>
    </main>
</div>
<?php get_footer(); ?>
functions.php
<?php

// 外観のメニュー表示
add_theme_support('menus');

// 外観のウィジェット表示
add_theme_support('widgets');

// カスタムロゴの表示
add_theme_support('custom-logo');

// タイトルタグの表示
add_theme_support('title-tag');

// アイキャッチの表示
add_theme_support('post-thumbnails');

// WordPressのバージョン情報
remove_action('wp_head', 'wp_generator');

// 絵文字
add_filter('emoji_svg_url', '__return_false');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');

// Windows Live Writeの停止
remove_action('wp_head', 'wlwmanifest_link');

// EditURI(RSD Link)の停止
remove_action('wp_head', 'rsd_link');

// 記号の自動変換停止(wptexturize無効化)
add_filter('run_wptexturize', '__return_false');

// https://api.w.org/の停止
remove_action('wp_head', 'rest_output_link_wp_head');

// global-styles-inline-cssの停止
remove_action('wp_enqueue_scripts', 'wp_enqueue_global_styles');
remove_action('wp_footer', 'wp_enqueue_global_styles', 1);
remove_action('wp_body_open', 'wp_global_styles_render_svg_filters');

// classic-theme-stylesの停止
add_action('wp_enqueue_scripts', function () {
    wp_dequeue_style('classic-theme-styles');
}, 20);

// wp-block-libraryの停止
add_action('wp_enqueue_scripts', function () {
    wp_dequeue_style('wp-block-library');
}, 20);

// メニューのliのid,classを削除
add_filter('nav_menu_css_class', 'wp_navtag_remove', 100, 1);
add_filter('nav_menu_item_id', 'wp_navtag_remove', 100, 1);
add_filter('page_css_class', 'my_css_attributes_filter', 100, 1);
function wp_navtag_remove($var) {
    return is_array($var) ? array_intersect($var, array('current-menu-item')) : '';
}

// メニュー位置の設定
function setup_nav_menu() {
    register_nav_menu('global_menu', 'グローバルメニュー');
    register_nav_menu('footer_menu', 'フッターメニュー');
}
add_action('after_setup_theme', 'setup_nav_menu');

// ウィジェットエリアの登録
function register_area() {
    register_sidebar([
        'name' => 'サイドバー',
        'id' => 'sidebar',
        'description' => 'サイドバーに表示されます。',
        'before_widget' => '<div id="%1$s" class="%2$s">',
        'after_widget' => '</div>',
    ]);
    register_sidebar([
        'name' => 'フッター',
        'id' => 'footer',
        'description' => 'フッターに表示されます。',
        'before_widget' => '<div id="%1$s" class="%2$s">',
        'after_widget' => '</div>',
    ]);
}
add_action('widgets_init', 'register_area');

// パンくずリスト
function breadcrumb() {
    $home = '<li><a href="' . get_bloginfo('url') . '">TOP</a></li>';
    echo '<ul class="breadcrumb">';

    // トップページ
    if (is_front_page()) {

        // カテゴリーページ
    } else if (is_category()) {
        $cat = get_queried_object();
        $cat_id = $cat->parent;
        $cat_list = array();
        while ($cat_id != 0) {
            $cat = get_category($cat_id);
            $cat_link = get_category_link($cat_id);
            array_unshift($cat_list, '<li><a href="' . $cat_link . '">' . $cat->name . '</a></li>');
            $cat_id = $cat->parent;
        }
        echo $home;
        foreach ($cat_list as $value) {
            echo $value;
        }
        the_archive_title('<li>', '</li>');

        // アーカイブページ
    } else if (is_archive()) {
        echo $home;
        the_archive_title('<li>', '</li>');

        // 投稿ページ
    } else if (is_single()) {
        $cat = get_the_category();
        if (isset($cat[0]->cat_ID)) $cat_id = $cat[0]->cat_ID;
        $cat_list = array();
        while ($cat_id != 0) {
            $cat = get_category($cat_id);
            $cat_link = get_category_link($cat_id);
            array_unshift($cat_list, '<li><a href="' . $cat_link . '">' . $cat->name . '</a></li>');
            $cat_id = $cat->parent;
        }
        echo $home;
        foreach ($cat_list as $value) {
            echo $value;
        }
        the_title('<li>', '</li>');

        // 固定ページ
    } else if (is_page()) {
        echo $home;
        the_title('<li>', '</li>');

        // 検索結果
    } else if (is_search()) {
        echo $home;
        echo '<li>「' . get_search_query() . '」の検索結果</li>';

        // 404ページ
    } else if (is_404()) {
        echo $home;
        echo '<li>ページが見つかりません</li>';
    }
    echo '</ul>';
}

//検索対象を投稿ページだけに
function search_filter($query) {
    if ($query->is_search) {
        $query->set('post_type', 'post');
    }
    return $query;
}
add_filter('pre_get_posts', 'search_filter');

// style.cssの読み込み
function enqueue_styles() {
    wp_enqueue_style('main-style', get_stylesheet_uri());
}
add_action('wp_enqueue_scripts', 'enqueue_styles');

まとめ

正直、見た目にこだわるといつまでたっても自作テーマが終わらないと避けていたのですが…

スマホの機能を作るにあたって、そろそろ見た目を整えないといけなかったので、ここでCSSを入れました。

見た目を整えると、この機能はいらないとか(サイドバーとか検索)この機能が欲しい(スマホの固定グローバルメニュー)

とかいろいろアイディアがでてくるので、ちょっとずつ実装していこうと思います。

Web制作のご依頼

SEOからデザインまで魅力的なWebサイトを制作いたします。

目次