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;
?>
さらに、
「これにカテゴリー’restaurant_menu_category’が’western_food’でさらにタグが’alacarte’のみを出力することは可能か?」
という質問
その解答
<?php
$args = array(
'post_type' => 'restaurant_menu',
'posts_per_page' => -1,
'tax_query' => array(
'relation' => 'AND', // 両方の条件を満たす投稿のみ
array(
'taxonomy' => 'restaurant_menu_category',
'field' => 'slug',
'terms' => 'western_food',
),
array(
'taxonomy' => 'restaurant_menu_tag', // タグのタクソノミー名(例)
'field' => 'slug',
'terms' => 'alacarte',
),
),
);
$menus = new WP_Query($args);
if ($menus->have_posts()) :
while ($menus->have_posts()) : $menus->the_post();
$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;
?>