Xwriteのカードにカスタムフィールド情報を表示するカスタマイズ

カスタマイズ
この記事は約4分で読めます。
記事内に広告が含まれています。

Xwrite 4.0.7

はじめに

Xwriteで、以下を実現します。

アーカイブページ→表示形式「カード表」のとき、カスタムフィールドに登録した情報を記事カード上に表示します。
抜粋の文字数が0以外に設定されている場合に表示されます。

この記事では、この方法について説明します。

完成イメージ

実装手順

以下のコードをfunctions.phpに追加します。

// 抜粋文を変更
add_filter('xwrite_post_excerpt_body', function ($excerpt_body) {
  // 固定ページは処理対象外
  if (get_post_type() === 'page') {
    return $excerpt_body;
  }

  $post_id = get_the_ID();

  // カテゴリー169以外は処理対象外
  if (!has_category(169, $post_id)) {
    return '';
  }

  // 評価値を取得
  $memo = get_post_meta($post_id, 'the_page_memo', true);

  if (!trim((string) $memo)) {
    $memo = '0,0,0,0,0';
  }

  $values = array_map('trim', explode(',', $memo));

  $labels = ['酸味', '苦味', '甘味', 'コク', '香り'];

  ob_start();
  ?>
  <table class="xw-article-meta">
    <thead>
      <tr>
        <th>項目</th>
        <th>評価</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach ($labels as $index => $label) : ?>
        <tr>
          <th scope="row"><?= esc_html($label); ?></th>
          <td><?= esc_html($values[$index]); ?></td>
        </tr>
      <?php endforeach; ?>
    </tbody>
  </table>
  <?php
  return ob_get_clean();
});


// フロント用JS・CSSを追加
add_action('wp_enqueue_scripts', function () {
  ob_start();
  ?>
  .xw-article-meta {
    border-collapse: collapse;
    width: 100%;

    & th,
    & td {
      border: 1px solid #ccc;
      padding: 8px 12px;
    }

    & thead th {
      background: #f5f5f5;
    }

    & tbody th {
      background: #fafafa;
    }

    & thead th,
    & td {
      text-align: center;
    }
  }
  <?php

  $handle = 'my-xwrite-rating-table';

  wp_register_style($handle, false);
  wp_enqueue_style($handle);
  wp_add_inline_style($handle, ob_get_clean());
});

さいごに

今回紹介した方法を使えば、Xwriteのアーカイブページで、表示形式が「カード表示」の記事カードにカスタムフィールドの情報を追加表示できます。
既存のフィルターを利用するため、テンプレートファイルを編集する必要はありません。
カスタムフィールドの情報を記事カードに表示したい場合に活用してみてください。

Cocoonでは、カードごとにテンプレートが用意されていて、カード内にもフックがあるから、カスタムフィールドの情報を追加するのも簡単なのにね。

タイトルとURLをコピーしました