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,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>';
?>

Advanced Custom Fieldsで数字を含む文字列の数字だけ半角にしてカンマを付ける

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

料金などの金額をacfで出力させるとき、単純に数字だけにできない場合がある。
具体的には、金額に幅があり~を付けなければならない状況。

例:acfのフィールド名は’room_price’

<?php
$price_raw = post_custom('room_price'); // 例: "12345~5678円"
$price_raw = mb_convert_kana($price_raw, 'n'); // 全角数字を半角に変換(例: "12345~5678円")

// 数字部分だけをカンマ付きに整形
$formatted_price = preg_replace_callback('/\d+/', function($matches) {
    return number_format($matches[0]);
}, $price_raw);

echo $formatted_price; // 例: "12,345~5,678円"
?>

これをテンプレートで使うと

<?php
$price_raw = post_custom('room_price'); // 例: "12345~5678円"
$price_raw = mb_convert_kana($price_raw, 'n'); // 全角数字を半角に変換(例: "12345~5678円")

// 数字部分だけをカンマ付きに整形
$formatted_price = preg_replace_callback('/\d+/', function($matches) {
    return number_format($matches[0]);
}, $price_raw);
?>
<table>
<tr>
<th>料金</th><td><?php echo $formatted_price; ?>円(税込)</td>
</tr>
</table>

WordPress固定ページでACFの画像を条件付きで出力する

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

Copilotに質問を投げかけた
「テンプレートファイルがpage-restaurant.phpでカスタム投稿タイプrestaurant_menu内にacfを使って画像のフィールド名をrestaurant_menu_imageとし、戻り値の形式は画像IDで出力したい。カスタム投稿タイプrestaurant_menuの投稿で画像がある場合のみ出力することはできるか?」

その解答

<?php
// カスタム投稿タイプ 'restaurant_menu' を取得
$args = array(
    'post_type' => 'restaurant_menu',
    'posts_per_page' => -1
);
$menus = new WP_Query($args);

if ($menus->have_posts()) :
    while ($menus->have_posts()) : $menus->the_post();

        // ACF画像フィールド(画像ID形式)を取得
        $attachment_id = get_field('restaurant_menu_image');
        if ($attachment_id) {
            $image = wp_get_attachment_image_src($attachment_id, 'large');
            $alt = get_post_meta($attachment_id, '_wp_attachment_image_alt', true);
            $caption = wp_get_attachment_caption($attachment_id);
            ?>
            <div class="menuItem">
                <h2><?php the_title(); ?></h2>
                <img src="<?php echo esc_url($image[0]); ?/>" alt="<?php echo esc_attr($alt); ?>" title="<?php echo esc_attr($caption); ?>">
            </div>
            <?php
        }

    endwhile;
    wp_reset_postdata();
else :
    echo '<p>メニューが見つかりませんでした。</p>';
endif;
?>

さらに、
(続きを読む…)

WordPressの集中執筆モードをデフォルトでOFFにする方法

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

投稿記事を書く時、通常の運用では集中執筆モードがデフォルトでオンになっており、表示オプションで集中執筆モードのチェックを外してオフにしても次にログインするとオンに戻ってしまう。
これをデフォルトではオフの状態にする方法。

functions.php
その1(こちらの方が記述がシンプル)
このコードは、エディターの自動拡張を無効にします。

function disable_editor_expand() {
    if ( is_admin() ) {
        wp_add_inline_script(
            'wp-blocks',
            'wp.data.dispatch("core/edit-post").removeEditorPanel("editor-post-publish-panel");'
        );
    }
}
add_action('admin_enqueue_scripts', 'disable_editor_expand');

その2(ログインするたびにオフにする記述)

/* ---------------------------------------------------------------------------------------
   ◆◆◆ 集中執筆モードをデフォルトでOFFにする ###########################################
------------------------------------------------------------------------------------------*/
function do_disable_editor_expand( $user_id ) {
    global $wpdb;
    $meta_key = $wpdb->prefix . 'user-settings';
    $_prev_user_settings = get_user_meta( $user_id, $meta_key, true );
    $_user_settings = explode( '&', $_prev_user_settings );
    $_is_override = false;

    foreach( $_user_settings as $_i => $_buff ) {
        list( $_key, $_val ) = explode( '=', $_buff );
        if ( 'editor_expand' === $_key ) {
            $_val = 'off';
            $_is_override = true;
        }
        $_user_settings[$_i] = $_key . '=' . $_val;
    }

    if ( ! $_is_override ) {
        $_user_settings[] = 'editor_expand=off';
    }

    update_user_meta( $user_id, $meta_key, implode( '&', $_user_settings ), $_prev_user_settings );
}

function custom_login_redirect( $redirect_to, $requested_redirect_to, $user ) {
    if ( ! is_wp_error( $user ) ) {
        global $user;
        if ( isset( $user->ID ) ) {
            do_disable_editor_expand( $user->ID );
        }
    }
    return $redirect_to;
}
add_filter( 'login_redirect', 'custom_login_redirect', 10, 3 );

function custom_user_register( $user_id ) {
    do_disable_editor_expand( $user_id );
}
add_action( 'user_register', 'custom_user_register' );

サイト内検索

カテゴリー

最近の投稿

↑上に戻る