BLOG

ブログ
  • Web制作

WordPressのget_template_partで読み込んだパーツファイルに変数を渡す方法

WordPressのget_template_partで 読み込んだパーツファイルに変数を渡す方法

はじめに

WordPressでテンプレートパーツを読み込む時に使用するのがget_template_part()関数です。

get_template_part()関数には、3つの引数を入れることができます。
(第二引数と第三引数は任意なので省略できます。)

get_template_part( $slug, $name, $args );

第一引数 $slug: テンプレートファイルのパス(例: ‘parts‘)
第二引数 $name: テンプレート名(任意)。-{$name}.phpが付いたファイルが読み込まれる。
第三引数 $args: 変数(任意/WordPress 5.5以降)。

$slug には読み込みたいファイル名(拡張子なし)を記述しますが、ファイルの場所はテーマファイルのフォルダから見た相対パスとなります。

例えば

  • parts-post.php
  • parts-page.php

と名前をつけたテンプレートを読み込む場合:

get_template_part( 'parts', 'post' );
get_template_part( 'parts', 'page' );

もしくは第二引数を使わずに以下のように書くこともできます。

get_template_part( 'parts-post' );
get_template_part( 'parts-page' );

また、「inc」フォルダにある parts-post.php ファイルを読み込みたい場合、以下のように記述します。

get_template_part( 'inc/parts', 'post' );
get_template_part( 'inc/parts-post' );

となります。

第三引数を指定して変数を渡す

WordPress5.5以降から第三引数を指定して変数を渡すことができるようになりました。

呼び出し側(親テンプレート)

$var = array(
	'num' => '090-000-0000',
	'mail' => 'xxx@sample.com'
);

get_template_part( 'parts', null, $var );

パーツファイル(例:parts.php

$num = $args['num'];
$mail = $args['mail'];

?>
<p><?php echo $num; ?></p>
<p><?php echo $mail; ?></p>

こうすることで以下のように表示されます。
090-000-0000
xxx@sample.com

また、archive.phpなどのループの中で連番を振ることもできます。

呼び出し側(親テンプレート)

<?php if (have_posts()) : ?>
    <?php $args = 1; ?>
    <?php while (have_posts()) : the_post(); ?>
        <?php get_template_part('parts', null, $args); ?>
        <?php $args++; ?> //$argsに+1する
    <?php endwhile; ?>
<?php endif; ?>

パーツファイル(例:parts.php

<div id="article-<?php echo $args; ?>"> //article-1 , article-2 , article-3 ・・・
    <a href="<?php the_permalink() ?>">
        <div class="img">
            <img src="<?php the_post_thumbnail(); ?>" alt="">
        </div>
        <h1 class="title"><?php the_title(); ?></h1>
        <div class="body"><?php the_content(); ?></div>
    </a>
</div>

こうすることで、ループの中でIDやクラス名に連番を付けることが可能です。
(article-1 , article-2 , article-3・・・)

変数名の注意点

注意点ですが、呼び出し側(親テンプレート)の変数名はどんな名前でもOK(上の例では $var)ですが、受け取り側(パーツファイル側)の変数名は必ず $args である必要があります。