WordPressのcontentを編集していると、特定の箇所だけPHPを記述して動的に表示したい場合があると思います。この記事では、ショートコードを自作して実現する方法を紹介します。
ショートコードの作成
適当な名前でショートコードを作ります。nameという属性に渡したテンプレート名を読み込むように、get_template_part関数を実行します。
add_shortcode('FILE', function ( $atts ) {
  $atts = shortcode_atts(array(
    'name' => '',
  ), $atts);
  if ( !$atts['name'] ) return;
  ob_start();
  get_template_part($atts['name']);
  return ob_get_clean();
});ショートコードを使う
実際にショートコードを使ってみます。
まず、今日の日付と曜日を表示するテンプレートをそれぞれ用意します。
<?php echo wp_date('Y-m-d');<?php echo wp_date('l');contentの任意の箇所にショートコードを挿入して、投稿を表示してみましょう。
今日の日付は「[FILE name="my_file1"]」です。
今日の曜日は「[FILE name="my_file2"]」です。テンプレートの内容が表示されているのが確認できました。
今日の日付は「2024-03-04」です。
今日の曜日は「月曜日」です。応用
WordPressのget_template_part関数でデータを渡すで紹介しましたが、get_template_part関数はインクルード元からデータを渡すことができます。
ショートコードに属性を追加して、明日の日付と昨日の曜日を取得してみましょう。
add_shortcode('FILE', function ( $atts ) {
  $atts = shortcode_atts(array(
    'name' => '',
    'args' => '',
  ), $atts);
  if ( !$atts['name'] ) return;
  
  $args = array();
  if ( $atts['args'] ) {
    $tmp = explode(':', $atts['args']);
    if ( isset($tmp[0]) && isset($tmp[1]) ) {
      $args[$tmp[0]] = $tmp[1];
    }
  }
  
  ob_start();
  get_template_part($atts['name'], null, $args);
  return ob_get_clean();
});<?php
  if ( isset($args['target_date']) ) {
    echo wp_date('Y-m-d', strtotime($args['target_date']));
  } else {
    echo wp_date('Y-m-d');
  }<?php
  if ( isset($args['target_date']) ) {
    echo wp_date('l', strtotime($args['target_date']));
  } else {
    echo wp_date('l');
  }ショートコードを使ってみます。
明日の日付は「[FILE name="my_file1" args="target_date:+1 day"]」です。
昨日の曜日は「[FILE name="my_file2" args="target_date:-1 day"]」です。表示できました。
明日の日付は「2024-03-05」です。
昨日の曜日は「日曜日」です。
  
  
  
  
コメント