概要
woocommerce_before_shop_loop_item_title
は、WooCommerceのショップループアイテムタイトルの前にフックされるアクションです。このアクションは、以下のような機能を実装する際によく使われます。
- 商品の価格を表示する
- 商品の評価を表示する
- 商品の販売状況(在庫状況)を表示する
- 商品のカスタムフィールドを表示する
- 商品のバッジ(新商品やセール中など)を表示する
- 商品の画像や動画をカスタマイズして表示する
構文
do_action('woocommerce_before_shop_loop_item_title');
パラメータ
woocommerce_before_shop_loop_item_title
アクションにはパラメータはありません。
戻り値
このアクションは何も値を返しません。フックを使って、特定のアクションや内容を表示するために使用されます。
バージョン
- WooCommerce: すべてのバージョンで使用可能
- WordPress: すべてのバージョンで使用可能
サンプルコード
サンプルコード1
add_action('woocommerce_before_shop_loop_item_title', 'custom_show_product_price');
function custom_show_product_price() {
global $product;
echo '<span class="price">' . $product->get_price_html() . '</span>';
}
このコードは、各商品タイトルの前に価格を表示するサンプルです。$product
オブジェクトを使用して、商品の価格を取得しています。
サンプルコード2
add_action('woocommerce_before_shop_loop_item_title', 'custom_show_product_rating');
function custom_show_product_rating() {
global $product;
echo '<div class="star-rating">' . $product->get_average_rating() . ' out of 5</div>';
}
このコードは、商品タイトルの前に商品の評価を表示します。商品の平均評価を取得し、適切な形式で表示します。
サンプルコード3
add_action('woocommerce_before_shop_loop_item_title', 'custom_show_stock_status');
function custom_show_stock_status() {
global $product;
if ($product->is_in_stock()) {
echo '<p class="stock in-stock">In Stock</p>';
} else {
echo '<p class="stock out-of-stock">Out of Stock</p>';
}
}
このコードは、商品の在庫状況を表示します。在庫がある場合は「In Stock」、ない場合は「Out of Stock」と表示します。
サンプルコード4
add_action('woocommerce_before_shop_loop_item_title', 'custom_show_product_badge');
function custom_show_product_badge() {
global $product;
if ($product->is_on_sale()) {
echo '<span class="onsale">Sale!</span>';
}
}
このコードは、セール中の商品に「Sale!」というバッジを表示します。商品がセール中であるかどうかをチェックしています。
サンプルコード5
add_action('woocommerce_before_shop_loop_item_title', 'custom_show_custom_field');
function custom_show_custom_field() {
global $product;
$custom_field = get_post_meta($product->get_id(), '_custom_field_key', true);
if (!empty($custom_field)) {
echo '<div class="custom-field">' . esc_html($custom_field) . '</div>';
}
}
このコードは、カスタムフィールドの値を表示します。指定されたカスタムフィールドが存在する場合、その値を表示します。
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
mu_plugin_loaded | |
registered_post_type | |
plugins_loaded | |
wp_roles_init | |
setup_theme | |
after_setup_theme | |
set_current_user | |
init | |
register_sidebar | |
wp_loaded | |
send_headers | |
parse_query | |
pre_get_posts | |
wp | |
template_redirect | |
get_header | |
wp_head |