WordPressでの独自テーマ作成#3(投稿記事の表示)

サムネイル
目次
  1. 今回やること
  2. お知らせ部分の作成
    • 投稿準備
    • 投稿の表示
  3. 一覧部分の作成(絞り込み有)
    • 投稿準備
    • 投稿の表示
  4. さいごに

今回やること

  • お知らせ部分を使用して作成
  • 一覧表示部分を「ACF」(Advanced Custom Fields)を使用して作成

お知らせ部分の作成

投稿準備

Localの管理画面からフォルダを開いてfunctions.phpを編集します。

<?php
function theme_name_scrips()
{
  wp_enqueue_style('style01', get_theme_file_uri("/css/style.css"));
}


add_action('init', function () {
  register_post_type('news', array(
    'labels' => array(
      'name' => 'お知らせ',
      'singular_name' => 'お知らせ',
    ),
    'public' => true,
    'has_archive' => true,
    'show_in_rest' => true,
  ));

  register_taxonomy(
    'news_category',
    'news',
    array(
      'label' => '内容',
      'hierarchical' => true,
      'show_ui' => true,
      'show_in_rest' => true,
    )
  );
});

add_action('wp_enqueue_scripts', 'theme_name_scrips');

保存したら左側メニューに「📌お知らせ」が追加されるので、「お知らせ」>「内容」から「イベント」「重要」などのカテゴリを作ります。

名前:イベント

スラッグ:event

他はそのままで保存

もう一つはお知らせですが、HTMLの方でclassと被ってしまうので名前=重要、スラッグ=importantで同じように作ってください。

「📌お知らせ」>「お知らせ」からブロックエディタを使ってタイトルとカテゴリを紐づけます。

右の表示は歯車マークをクリックで表示できます。

例文

タイトル内容
○○○を開催します。イベント
○月○日はメンテナンスを行います。重要
○月○日はメンテナンスを行います。重要

この3行を追加してください。

これでお知らせ部分の下準備ができました。

投稿の表示

front-page.phpに移動して編集します。

phpは<ul>の中に記述していきます。

<div class="l-news">
            <h2 class="c-heading">お知らせ</h2>
            <ul class="c-news-list">

                <?php
                $news = array(
                    "post_type" => "news",
                    "posts_per_page" => 3,
                    "post_status" => "publish",
                );

                $the_query = new WP_Query($news);
                ?>
                <?php
                if ($the_query->have_posts()) :
                    while ($the_query->have_posts()) : $the_query->the_post();
                ?>

                        <li>
                            <a href="">
                                <span class="c-news-list__date"><?php echo get_the_date();?></span>
                                <p class="c-news-list__category"><?php $the_terms = get_the_terms($post->ID, "news_category");
                                                                    echo $the_terms[0]->name; ?></p>
                                <p class="c-news-list__title"><?php the_title(); ?></p>
                            </a>
                        </li>
                <?php
                    endwhile;
                endif;
                wp_reset_postdata();
                ?>
            </ul>
        </div>

このままでは日付の部分が微妙なので「設定」>「一般」から「日付形式」をカスタムにチェックで、中身を[Y.m.d]に変更します。

これでお知らせ部分は完成です

参考サイト

投稿の日付を取得し、表示する / 日付のフォーマットを変更する

一覧部分の作成(絞り込み有)

投稿準備

お知らせ部分と同様にfunctions.phpを編集します。

register_taxonomy();直下に追加してください。

register_post_type('greengrocery', array(
    'labels' => array(
      'name' => '青果物',
      'singular_name' => '青果物',
    ),
    'public' => true, 
    'has_archive' => true, 
    'show_in_rest' => true, 
    'supports' => array('title', 'editor', 'thumbnail') //初期値は('title', 'editor')
  ));

  register_taxonomy(
    'greengrocery_category',
    'greengrocery',
    array(
      'label' => '青果物カテゴリー',
      'hierarchical' => true,
      'show_ui' => true,
      'show_in_rest' => true,
    )
  );

保存したら左側メニューに「📌青果物」が追加されます。

前回、「ACF」のプラグインを追加していたら、左側メニューに「カスタムフィールド」が表示されています。表示が無い場合は、前回の記事を確認しながらプラグインの追加・有効化がされているか確認してみてください。

カスタムフィールドの新規追加からニュースのカテゴリに当たる部分の準備をしていきます。

青果物カテゴリ表

タイトル青果物
フィールドタイプテキスト
フィールドラベル価格
フィールド名price

他はそのままで保存後、「価格」というラベル名で追加されているのが確認できます。

少し下を見るとルールという欄があるので、「投稿タイプ」、「等しい」、「青果物情報」に変更してください。

お知らせと同じようにカテゴリも「果物」と「野菜」を追加します。

青果物カテゴリ表

名前スラッグ
果物fruits
野菜vegetables

青果物情報もブロックエディタを使って下のように6個追加してください。

※値段はお任せします

青果物一覧表

名前カテゴリ値段アイキャッチ画像
イチゴ果物お任せimg_01.jpg
ブルーベリー果物お任せimg_02.jpg
ライム果物お任せimg_03.jpg
トマト野菜お任せimg_04.jpg
キュウリ野菜お任せimg_05.jpg
ニンジン野菜お任せimg_06.jpg

投稿の表示

front-page.phpを編集します。

絞り込みのために<h2>の後にformを追加しています。

<div class="product">
            <h2 class="c-heading">青果物一覧</h2>
            <form class="c-form" action="<?php echo home_url(); ?>" method="GET">
                <select name="category">
                    <option value="" >種類</option>
                    <?php
                            $terms = get_terms("greengrocery_category"); 
                            if($terms){
                                foreach($terms as $term){
                                    print_r($term);
                    ?>
                    <option <?php selected($_GET["category"],$term->term_id);?> value="<?php echo $term->term_id;?>"><?php echo $term->name;?></option>
                    <?php
                                }
                            }
                    ?>
                </select>
                <button type="submit">送信</button>
            </form>
            <ul class="c-ploduct">
            <?php
                    $greengrocery_category = (isset($_GET["category"])?(int)$_GET["category"]:"");
                    $greengrocery = array(
                        'post_type' =>'greengrocery',
                        'posts_per_page'=>6,
                    );

                    if($greengrocery_category){
                        $greengrocery["tax_query"][]=[
                            "taxonomy"=>"greengrocery_category",
                            "terms"=>$greengrocery_category,
                            "operator"=>"IN",
                            "field"=>"term_id",
                        ];
                    }
                    $the_query = new WP_Query($greengrocery);
                ?>
                <?php
                    if ($the_query->have_posts()): 
                    while($the_query->have_posts()) : $the_query->the_post(); 
                ?>
                    <li>
                        <a href="">
                            <div class="c-ploduct__image">
                                <?php the_post_thumbnail("thumbnail"); ?>
                            </div>
                            <p class="c-ploduct__category"><?php $the_terms = get_the_terms($post->ID,"greengrocery_category");
                            echo $the_terms[0]->name; ?></p>
                            <p class="c-ploduct__title"><?php the_title(); ?></p>
                            <p class="c-ploduct__price"><?php echo get_field("price"); ?>円</p>
                        </a>
                    </li>
                <?php 
                    endwhile;  
                    endif;wp_reset_postdata();
                ?>
        </div>

確認して、絞り込みも問題なければこれで一覧部分も完成です。

後々、参考にしたリファレンス等の追加・修正していきます

さいごに

今回の記事では、Advanced Custom Fieldsを使って投稿の表示をしました。

次回の記事では、お問い合わせ、その他調整をしていきます。