概要
woocommerce_before_single_product
は、WooCommerceの商品詳細ページが表示される前に実行されるフックです。このアクションは、商品情報の表示前に追加のコンテンツや機能を挿入するために広く使用されます。具体的には以下のような機能を実装する際によく使われます。
- 商品情報の前に特別なメッセージやバナーを追加する。
- 関連商品やおすすめ商品の表示をカスタマイズする。
- コンテンツの分析やトラッキングコードを挿入する。
- 商品のプロモーションや特集のためのカスタムデザインを追加する。
- 商品詳細ページにカスタムフィールドを表示する。
- 他のプラグインとの連携機能を挿入する。
構文
add_action('woocommerce_before_single_product', 'your_custom_function');
パラメータ
このアクションにはパラメータはありません。
戻り値
戻り値も特にありませんが、実行されるカスタム関数は、HTMLを出力や他の側面を変更することができます。
使用可能なプラグインWooCommerceのバージョン
- WooCommerce 3.0以降
ワードプレスのバージョン
- WordPress 4.0以降
サンプルコード
サンプルコード 1: カスタムメッセージを追加
add_action('woocommerce_before_single_product', 'add_custom_message');
function add_custom_message() {
echo '<div class="custom-message">特別プロモーション中!</div>';
}
このコードは、商品詳細ページの最初に特別なプロモーションメッセージを表示します。
サンプルコード 2: SNSシェアボタンの挿入
add_action('woocommerce_before_single_product', 'add_social_share_buttons');
function add_social_share_buttons() {
echo '<div class="social-buttons">シェアする: <a href="#">Facebook</a> | <a href="#">Twitter</a></div>';
}
このコードは、商品詳細ページの上部にSNSシェアボタンを追加します。
サンプルコード 3: 関連商品のセクションをカスタマイズ
add_action('woocommerce_before_single_product', 'customize_related_products');
function customize_related_products() {
echo '<h2>おすすめ商品</h2>';
// ここに関連商品の出力ロジックを追加
}
このコードは、関連商品のセクションをカスタマイズし、見出しを追加します。
サンプルコード 4: トラッキングコードの挿入
add_action('woocommerce_before_single_product', 'insert_tracking_code');
function insert_tracking_code() {
echo '<script>console.log("商品ページ訪問者");</script>';
}
このコードは、商品詳細ページを訪れたユーザーのトラッキング用のJavaScriptコードを挿入します。
サンプルコード 5: 商品ページにカスタムフィールドを表示
add_action('woocommerce_before_single_product', 'show_custom_product_field');
function show_custom_product_field() {
global $product;
$custom_field = get_post_meta($product->get_id(), '_custom_field_key', true);
if ($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 |