YouTube 〜 WordPress連結講座#4 〜 コードメモ
2020/12/29
WordPress連結講座#4で取り扱ったソースコードの一部をメモ程度にご紹介します。
functions.phpでカスタム投稿タイプを管理画面に追加するコード
下記コードをfuntions.phpに書くことでworksというカスタム投稿タイプを追加(動画7:26あたり)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?php // functions.phpの先頭はphpタグで始める(閉じタグはなくてもOK) function cpt_register_works() { //add_actionの2つのパラメーターを定義 $labels = [ "singular_name" => "works", "edit_item" => "works", ]; $args = [ "label" => "Works", //管理画面に出てくる名前 "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" => "works", "with_front" => true ], //スラッグをworksに設定 "query_var" => true, "menu_position" => 5, "supports" => [ "title", "editor", "thumbnail" ], ]; register_post_type( "works", $args ); } add_action( 'init', 'cpt_register_works' ); |
カスタム投稿タイプにカテゴリーを追加するコード
下記コードをfunctions.phpに追記することで(上記コードがある前提)、カスタム投稿タイプにカテゴリーを追加(動画17:35あたり)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
function cpt_register_dep() { //add_actionの2つのパラメーターを定義 $labels = [ "singular_name" => "dep", ]; $args = [ "label" => "カテゴリー", "labels" => $labels, "publicly_queryable" => true, "hierarchical" => true, "show_in_menu" => true, "query_var" => true, "rewrite" => [ 'slug' => 'dep', 'with_front' => true, ], //カテゴリーのスラッグ "show_admin_column" => false, "show_in_rest" => true, "rest_base" => "dep", "rest_controller_class" => "WP_REST_Terms_Controller", "show_in_quick_edit" => false, ]; register_taxonomy( "dep", [ "works" ], $args ); //「works」というカスタム投稿タイプにカテゴリーを追加 } add_action( 'init', 'cpt_register_dep' ); |
トップページに制作実績一覧を追加するコード
下記コードをfront-page.phpに追記することで、トップページに制作実績一覧を表示(動画21:30あたり)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<section class="works_list"> <div class="head">制作実績</div> <div class="news_list"> <?php $args = array( 'post_type' => 'works', // 投稿タイプスラッグ 'posts_per_page' => 3 ); $the_query = new WP_Query($args); // データベースを検索して引っ張ってくる情報を作成($argsで必要な情報を配列にして渡している) ?> <ul> <?php if($the_query->have_posts()): while ($the_query->have_posts()): $the_query->the_post(); ?> <li> <a href="<?php the_permalink() ;?>"> <div class="img"><img src="<?php echo CFS()->get('thumbnail') ;?>" alt=""></div> <div class="type">業種:<?php echo CFS()->get('type') ;?></div> <div class="client">クライアント:<?php echo CFS()->get('client') ;?></div> </a> </li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); ?> <?php else: ?> <?php endif; ?> <div class="btn_stn"><a href="<?php bloginfo('url') ;?>/works">一覧をみる</a></div> </div> </section> |