超絶初心者(自分)のためのWordPressのテーマ作成-7
今回はWordpressの投稿フォーマット機能を追加し、実装するかについて書いていきます。
まずは以下のコードをfunctions.phpに追加していきます。
add_theme_support('post-formats');
functions.phpの追加後のコード
<?php
function my_theme_script_enqueue(){
wp_enqueue_style('customstyle', get_template_directory_uri() . '/css/my_theme.css', array(), '1.0.0', 'all');
wp_enqueue_script('customjs', get_template_directory_uri() . '/js/my_theme.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_script_enqueue');
function my_theme_setup(){
// 外観(Apperance)からカスタムメニューを見えるようにする
add_theme_support('menus');
//ここカスタムメニューを定義する。 register_nav_menu('場所','説明')
register_nav_menu('primary', 'Header Navigation');
register_nav_menu('secondary', 'Footer Navigation');
}
add_action('init', 'my_theme_setup');
add_theme_support('custom-background');
add_theme_support('custom-header');
add_theme_support('post-thumbnails');
add_theme_support('post-formats');
そうすると投稿画面に以下のように投稿フォーマットという表示が現れます。

しかしこのままだとまだ何も選択できないので、第2引数にarrayでどのフォーマットを使いたいかを渡す。
add_theme_support('post-formats',array('aside', 'image', 'video'));
これを追加することによって、先ほどまで標準しかなかったがアサイド、画像、動画も設定できるようになる。

なぜこれが便利かというのはこれからわかります。
ここで少しget_post_format()関数について
この関数は読んで字の如く投稿フォーマット返す関数です。
例えば投稿ページで画像を選んだらimageという文字列、動画を選んだらvideoという文字列を返し、標準を選んだ場合空白文字列を返します。
それでは次にindex.phpをこのように書き換えます。
<?php get_header(); ?>
<?php
if(have_posts()):
while(have_posts()): the_post(); ?>
<?php get_template_part('content', get_post_format());?>
<?php endwhile;
endif;
?>
<?php get_footer(); ?>
そして先ほどまでそこに書かれていたコードを新しくcontent.phpというファイルを作りそこに書き込みます。
content.phpのコード
<h3><?php the_title() ?></h3>
<div class="thumbnail-img"><?php the_post_thumbnail('thumbnail') ?></div>
<!-- the_time()で記事の投稿された時間を表示し、the_category()で記事のカテゴリーを表示 -->
<small>Posted on: <?php the_time(); ?><?php the_category(); ?> </small>
<p><?php the_content() ?></p>
<hr>
最近のコメント