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「post_per_page」で取得数が指定できない場合の対処

Filed under: php,wordpress — kdcs @ 24年7月5日 金曜日

通常のnew WP_Query内にpost_per_pageで取得するpost数を指定してもダッシュボード>設定>表示設定で指定した表示数になってしまうので以下の記述で対応。

<?php
$query = new WP_Query(
    $args = array(
        'post_type' => 'post',
        'post_per_page' => 3,
    )
);
$query->post_count = 3;
if ( $query->post_count > count( $query->posts ) ) :
	$query->post_count = count( $query->posts );
endif; ?>

<?php if($query -> have_posts()): while($query -> have_posts()): $query -> the_post(); ?>
// ループさせる内容
<?php else : ?>
// 記事が無い場合の記述
<?php endif; wp_reset_postdata(); ?>

Advanced Custom Fieldsのテキストエリア内にある改行を削除する

Filed under: php — kdcs @ 24年2月29日 木曜日

Advanced Custom Fieldsのテキストエリアは改行の設定ができるので通常はテキストエリアの入力時に開業すれば自動的にbrタグが入るようになっている。改行設定しているにもかかわらずテキストエリア内にbrタグを書き込むと、出力時にPHPで「mb_substr」にしても完全にbrタグが取り除けない事案が発生。

これ(brタグを全て削除)を解決するための方法
※文字数40で、文字の後に「…」を入れる

<?php
$text = get_field('カスタムフィールド名');
$str = str_replace(array('<br>','<br />',"\r\n","\n","\r",' '),'',$text);
$mbtext = mb_substr(($str),0,30,'utf-8');
echo $mbtext.'...';
 ?>

カスタム投稿タイプのパンくず

Filed under: php,wordpress — kdcs @ 21年5月6日 木曜日

カスタム投稿タイプのカテゴリーと年月アーカイブにパンくずリストを付ける

例:パーマリンクがblog

<?php /* パンクズリストここから----------------------------------------------------------- */ ?>
<div id="breadcrumb" class="bread">
<ol>
<li><a href="<?php echo home_url(); ?>/blob">カスタム投稿タイプのブログ</a></li>
<li>
  <?php
    if(is_category() || is_tag() ) {
      if( $cat ) {
	  $catdata = get_category( $cat );
	if( $catdata->parent ) {
	  echo get_category_parents( $catdata->parent, true, '</li><li>' );
    }
  }
      echo '<a>',single_term_title(),'</a>';
  } elseif(is_year()) {
      echo '<a>',get_query_var('year'),'年</a>';
  } elseif(is_month()) {
    $year = get_query_var('year');
      echo '<a href="',get_year_link( $year ),'">',$year,'年</a></li>';
      echo '<li><a>',get_query_var('monthnum'),'月</a>';
  } elseif(is_day()) {
    $year = get_query_var('year');
    $month = get_query_var('monthnum');
      echo '<a href="',get_year_link( $year ),'">',$year,'年</a></li>';
      echo '<li><a href="',get_month_link( $year,$month ),'">',$month,'月</a></li>';
      echo '<li><a>',get_query_var('day'),'日</a>';
  }
?>
</li>
</ol>
</div><!--/#breadcrumb.bread-->
<?php /* パンクズリストここまで----------------------------------------------------------- */ ?>

上記の記述だとカスタム投稿タイプのカテゴリーページでは出力されないので
以下をtaxonomy-xxxx_category.phpに記述

<?php /* パンクズリストここから----------------------------------------------------------- */ ?>
<div id="breadcrumb" class="bread">
<ol>
<li><a href="<?php echo home_url(); ?>/blob">スタッフブログ</a></li>
<li><?php echo single_term_title(); ?></li>
</ol>
</div><!--/#breadcrumb.bread-->
<?php /* パンクズリストここまで----------------------------------------------------------- */ ?>

サイト内検索

カテゴリー

最近の投稿

↑上に戻る