概要
product_variation_linked
フィルタは、WooCommerce プラグイン内で商品バリエーションのリンクを表示する際に用いられます。このフィルタを使用することにより、商品のバリエーションの表示方法をカスタマイズすることが可能です。具体的には、以下のような機能に利用されることが多いです。
- バリエーションの表示順序を変更する
- 特定の条件に基づいてバリエーションのリンクを変更する
- バリエーションのリンクに追加情報を付与する
- バリエーションの選択肢を動的に変更する
- バリエーションの画像をカスタマイズして表示する
- 商品のバリエーションを条件付きで非表示にする
構文
add_filter('product_variation_linked', 'your_custom_function', 10, 2);
パラメータ
$linked
(string): 現在のバリエーションリンク。$product
(WC_Product): 現在の製品オブジェクト。
戻り値
- (string): フィルタを通じて変更されたバリエーションリンク。
使用可能なバージョン
- WooCommerce: 3.0 以上
- WordPress: 4.0 以上
この関数のアクションでの使用可能性
アクション | 使用可能性 |
---|---|
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 |
サンプルコード
サンプル1: バリエーションリンクにカスタムクラスを追加する
add_filter('product_variation_linked', 'add_custom_class_to_variation_link', 10, 2);
function add_custom_class_to_variation_link($linked, $product) {
return str_replace('<a', '<a class="custom-class"', $linked);
}
このコードは、商品バリエーションのリンクにカスタムクラスを追加しています。これにより、CSSなどでスタイルを変更することができます。
サンプル2: バリエーションリンクを変更する
add_filter('product_variation_linked', 'modify_variation_link', 10, 2);
function modify_variation_link($linked, $product) {
return '<a href="' . esc_url($product->get_permalink()) . '" target="_blank">Buy Now</a>';
}
このコードでは、バリエーションリンクを「Buy Now」に変更し、別タブで開くように設定しています。
サンプル3: 特定のIDのバリエーションを非表示にする
add_filter('product_variation_linked', 'hide_specific_variation', 10, 2);
function hide_specific_variation($linked, $product) {
if ($product->get_id() === 123) { // IDが123の場合
return '';
}
return $linked;
}
このコードは、特定のバリエーション(ID 123)のリンクを非表示にします。
サンプル4: バリエーションリンクに現在の在庫状況を追加する
add_filter('product_variation_linked', 'add_stock_status_to_variation_link', 10, 2);
function add_stock_status_to_variation_link($linked, $product) {
if (!$product->is_in_stock()) {
return $linked . ' <span class="out-of-stock">(Out of stock)</span>';
}
return $linked;
}
このコードは、在庫がない場合に「(Out of stock)」というテキストをバリエーションリンクの後に追加しています。
サンプル5: デフォルトのバリエーションリンクをカスタマイズ
add_filter('product_variation_linked', 'custom_default_variation_link', 10, 2);
function custom_default_variation_link($linked, $product) {
$default_variation = $product->get_default_attributes();
return '<a href="' . esc_url($product->get_permalink($default_variation)) . '">View Default Variation</a>';
}
このコードは、商品のデフォルトバリエーションリンクをカスタマイズし、「View Default Variation」というテキストで表示します。
参考URL
- https://woocommerce.com/document/using-hooks/ (WooCommerceハンドブック)
- https://developer.wordpress.org/reference/functions/add_filter/ (WordPress関数リファレンス)