WordPressテーマ内のファイルに別ファイル読み込み「include」ほか

Filed under: php,wordpress — kdcs @ 25年11月28日 金曜日

テーマ内のテンプレートファイルに別ファイルを読み込ませる場合、今までは「TEMPLATEPATH.」を使っていたが、WordPress 6.4.0 以降では 非推奨 になっているのでその代替の手法。

今までの記述

<?php include(TEMPLATEPATH.'/hogehoge.php'); ?>

その1.「include get_template_directory()」を使う

<?php include get_template_directory() . '/hogehoge.php'; ?>

その2.WordPress 標準のテンプレート読み込み関数「get_template_part() 」を使う

get_template_part('hogehoge');

hogehoge.phpが、hogehoge-news.phpのようにハイフン付きのファイル名の場合

get_template_part('hogehoge', 'news');

<?php 
/*
  list.php
  list-news.php
  を読み込む
*/
  get_template_part('list'); 
  get_template_part('list', 'news'); 

/*
  parts/list.php
  parts/list-news.php
  を読み込む
*/
  get_template_part('parts/list'); 
  get_template_part('parts/list', 'news'); 
?>

Advanced Custom Fieldsで~を使った範囲のある金額表示

Filed under: php — kdcs @ 25年10月6日 月曜日

数字で入力した金額にカンマを付けたり、前に~や後ろに~を付けるだけでなく4000~10000など範囲のある金額を表示させる方法。

~が3種類(チルダmac・波ダッシュwindows・半角チルダ)あるため、~に絞らず数字だけ抽出して半角とカンマ処理させることにした。最終的に金額の後ろに円を付ける。

※例は宴会プラン用(banquet_price・banquet_tilde_position)

<?php
$price_raw = get_field('banquet_price'); // 例: "4000~10000" や "4000"
$tilde = get_field('banquet_tilde_position'); // 「before」「after」「none」

if ($price_raw) {
    // 全角数字を半角に変換
    $price_raw = mb_convert_kana($price_raw, 'n');

    // 数字部分だけ抽出してカンマを付ける
    $price_text = preg_replace_callback('/\d+/', function($matches) {
        return number_format($matches[0]);
    }, $price_raw);

    // 「円」を最後に追加
    $price_text .= '円'
;
    // 「~」の位置を制御
    if ($tilde === 'before') {
        $formatted_banquet_price = '~' . $price_text;
    } elseif ($tilde === 'after') {
        $formatted_banquet_price = $price_text . '~';
    } else {
        $formatted_banquet_price = $price_text;
    }
}
?>

advanced custom fieldsで画像フィールドが複数あるときの出力方法

Filed under: php,wordpress — kdcs @ 25年9月5日 金曜日

acfで画像フィールドが複数あり、返り値がidの場合の出力

room_img1~room_img6まで画像フィールドがある場合
※画像サイズは複数(largeとthumbnail)に対応

<?php
$size_large = 'large';
$size_thumb = 'thumbnail';

$images = [];

for ($i = 1; $i <= 6; $i++) {
    $field = 'room_img' . $i;
    $attachment_id = get_field($field);

    if ($attachment_id) {
        $image_large = wp_get_attachment_image_src($attachment_id, $size_large);
        $image_thumb = wp_get_attachment_image_src($attachment_id, $size_thumb);
        $attachment = get_post($attachment_id);
        $alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
        $caption = get_the_excerpt($attachment);

        // 念のため画像URLが取得できているかも確認
        if ($image_large && $image_thumb) {
            $images[] = [
                'large' => $image_large[0],
                'thumb' => $image_thumb[0],
                'alt' => esc_attr($alt),
                'caption' => esc_html($caption)
            ];
        }
    }
}
?>

テンプレートの出力部はswiperでスライドさせる場合

<div class="swiper-wrapper">
<?php foreach ($images as $img): ?>
    <div class="swiper-slide">
        <img src="<?php echo $img['src']; ?/>" alt="<?php echo $img['alt']; ?>" title="<?php echo $img['caption']; ?>">
        <?php if ($img['caption']): ?>
            <span><?php echo $img['caption']; ?></span>
        <?php endif; ?>
    </div>
<?php endforeach; ?>
</div><!--/.swiper-wrapper-->

(続きを読む…)

advanced custom fieldsでテキストエリアの内容をリストタグで出力する方法

Filed under: php,wordpressプラグイン — kdcs @ 25年8月27日 水曜日

advanced custom fieldsでテキストエリアの内容をリストタグで出力する方法

<?php
// ACFのフィールド名を指定
$text = get_field('your_field_name');

if ($text) {
    // 改行で分割(Windows環境なども考慮して\r\nも含める)
    $lines = preg_split('/\r\n|\r|\n/', $text);

    echo '<ul>';
    foreach ($lines as $line) {
        // 空行を除外し、余分な空白を除去してエスケープ
        if (trim($line) !== '') {
            echo '<li>' . esc_html(trim($line)) . '</li>';
        }
    }
    echo '</ul>';
}
?>

「preg_split(‘/\r\n|\r|\n/’, $text)」:改行コードの違いに対応(Windows, macOS, Linux)

「trim($line) !== ”」:空行を除外

「esc_html()」:HTMLエスケープで安全に出力

「ul」タグでリスト化

Advanced Custom Fieldsのテキストエリアをテーブルとして使う方法

Filed under: php,wordpress,wordpressプラグイン — kdcs @ 25年8月21日 木曜日

Advanced Custom Fieldsのテキストエリアをテーブルとして使う方法

PHP 8.3では、null を文字列関数に渡すことが非推奨になっているので「null チェック」を入れる必要がある

テーブルはthとtdの2列だけで、行は何行になってもOK。thとtdの値は半角の@(アットマーク)で区切る
※当初:(コロン)で区切っていたが時間表示でコロンが使われる可能性があるので@に変更した

<?php
// データを取得(nullの可能性がある)
$field = get_field('catering_option') ?? '';

// 連続した改行を1つの改行にまとめる
$field = preg_replace('/(\n|\r|\r\n)+/us', '\n', $field);
// もし全角の:があれば半角の:に変換する
$field = str_replace('@', '@', $field);

// 1行ごとに<tr>、「@」で<th>と<td>に区切る
echo '<table>
    <tr>
        <th>' .
        str_replace(
            array('\n', '@'),
            array('</td></tr><tr><th>', '</th><td>'),
            $field
        ) .
        '</td>
    </tr>
</table>';
?>

これに以下の処理を追加
・@を付けない行はテーブルのセルtdを結合する処理を行う(colspan=”2″)
・結合したtdにclass=”td_comment”を付ける
・空の行は無視する

<?php
$field = get_field('catering_info') ?? '';
$field = preg_replace('/(\n|\r|\r\n)+/us', "\n", $field);
$field = str_replace('@', '@', $field);

$lines = explode("\n", $field);
echo '<table>';
foreach ($lines as $line) {
    $line = trim($line);
    if ($line === '') {
        continue;
    }

    echo '<tr>';
    if (strpos($line, '@') !== false) {
        list($th, $td) = explode('@', $line, 2);
        echo '<th>' . htmlspecialchars($th) . '</th>';
        echo '<td>' . htmlspecialchars($td) . '</td>';
    } else {
        // class="td_comment" を追加
        echo '<td colspan="2" class="td_comment">' . htmlspecialchars($line) . '</td>';
    }
    echo '</tr>';
}
echo '</table>';
?>

サイト内検索

カテゴリー

最近の投稿

↑上に戻る