初学者向けWordPressカスタム投稿の追加の方法

1,カスタム投稿とは

デフォルトのブログ投稿機能に加えて、投稿機能を追加することです。ブログ機能としてだけではなく、商品情報やスタッフ紹介など活用方法があります。

2,functions.phpに関数を記述する

今回は、商品という名前で追加します。

実際のコード

function cpt_add_item() { //add_actionの2つのパラメーターを定義
	$labels = [
		"singular_name" => "item",
		"edit_item" => "item",
	];
	$args = [  //配列を定義
		"label" => "商品", //管理画面に出てくる名前
		"labels" => $labels,
		"description" => "商品一覧",//投稿タイプの簡潔な説明
		"public" => true,
		"show_in_rest" => true,
		"rest_base" => "",
		"rest_controller_class" => "WP_REST_Posts_Controller",
		"has_archive" => true, //アーカイブページ
		"delete_with_user" => false,
		"exclude_from_search" => false,
		"map_meta_cap" => true,
		"hierarchical" => true,//親子関係
		
		"rewrite" => [ "slug" => "item", "with_front" => true ], //スラッグをitemに設定
		"query_var" => true,
		"menu_position" => 5,
		"supports" => [ "title", "editor", "thumbnail", "customfields" ],
		'menu_icon' => 'dashicons-store',//wp公式アイコン
	];
	register_post_type( "item", $args );//カスタム投稿タイプを追加する関数
}
add_action( 'init', 'cpt_add_item' );

次にWordPressの管理画面を確認します。

商品が投稿の下に表示されました。

3,次にアーカイブを表示させます。

デフォルトの投稿でメインループを使っているのでここでは、サブループを使います。

front-page.phpやarchive-item.phpなどファイルを作成して下記のコードを出力したい箇所に記述しましょう。

     <!-- サブループをここに記入 -->
        <?php
        $args = array(
        'post_type' => 'item',//投稿タイプを指定
        'posts_per_page' => 5,//記事の数を指定
        ); ?>

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

        <li class="post__item">
          <!-- パーマリンクを追記 -->
          <a href="<?php the_permalink(); ?>/">
            <div class="post__item-text-wrap">
              <span class="post__item-date"><?php the_time('Y.m.j'); ?></span><span class="post__item-cat">自然</span>
              <h3 class="post__item-title">
                <?php the_title(); ?>
              </h3>
              <div class="post__item-desc">
                <?php the_content(); ?>
              </div>
            </div>
            <?php wp_reset_postdata(); ?>
            <?php endwhile; else: ?>
            <?php endif; ?>
          </a>
        </li>
      </ul>

arrayの()の中のパラメータは様々な機能を追加できるので、調べて追加しても良いかもしれません。