title | emoji | type | topics | published | |
---|---|---|---|---|---|
WordPress引数を渡して部分テンプレートを読み込む方法 |
😌 |
tech |
|
true |
2020/12/31 version 5.5から引数が渡せるようになりました https://make.wordpress.org/core/2020/07/17/passing-arguments-to-template-files-in-wordpress-5-5/
get_template_part( "articles", null, array( "title" => "タイトル" ) );
echo esc_html( $args["title"] );
複数の場合はarray
の中身を増やせばOK
get_template_part( "articles", null, array( "title" => "タイトル","description" => "ディスクリプション" ) );
ちなみにversion 5.5以前の場合だとこんな感じで書いてました
functions.php などに
function get_template_part_args($template_name, $args = null) {
if (isset($args)) {
foreach ($args as $key => $value) {
set_query_var($key, $value);
}
}
get_template_part($template_name);
}
を書いて
get_template_part_args( "articles", array( "title" => "タイトル" ) );
echo esc_html( $args["title"] );
set_query_var
の関数リファレンスはこちら。
https://developer.wordpress.org/reference/functions/set_query_var/