概要
woocommerce_single_product_image_thumbnail_html
フィルタは、WooCommerceによって提供されるフックで、単一商品の画像サムネイルのHTML出力を変更するために使用されます。このフィルタは、商品のサムネイル画像の視覚的なプレゼンテーションや属性を調整したい場合に便利です。よく使われる主な機能は以下の通りです:
- サムネイル画像のクラスをカスタマイズする。
- サムネイルにラベルやテキストを追加する。
- 商品が特定の条件を満たす場合に異なるスタイルを適用する。
- サムネイル画像を別の画像やリンクに変更する。
- 商品ごとに異なる表示スタイルを適用する。
- レスポンシブデザインのためのカスタム属性を追加する。
構文
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'custom_thumbnail_html', 10, 2 );
パラメータ
$html
(string): 生成されたサムネイル画像のHTML。$post_id
(int): 現在の投稿(商品)のID。
戻り値
- (string): 修正されたサムネイル画像のHTML。
バージョン
このフィルタは、WooCommerceバージョン2.0以降で使用可能です。また、WordPressバージョン3.6以降で動作します。
サンプルコード
サンプルコード1: サムネイルにカスタムクラスを追加
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'add_custom_class_to_thumbnail', 10, 2 );
function add_custom_class_to_thumbnail( $html, $post_id ) {
$html = str_replace( 'class="', 'class="custom-thumbnail-class ', $html );
return $html;
}
このコードは、サムネイル画像のHTMLにカスタムクラスを追加します。
サンプルコード2: サムネイルにテキストを追加
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'add_text_to_thumbnail', 10, 2 );
function add_text_to_thumbnail( $html, $post_id ) {
$text = '<span class="custom-text">新商品</span>';
return $text . $html;
}
このコードは、サムネイル画像の前に「新商品」というテキストを追加します。
サンプルコード3: 特定の条件で画像を変更
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'change_thumbnail_based_on_condition', 10, 2 );
function change_thumbnail_based_on_condition( $html, $post_id ) {
if ( get_post_meta( $post_id, '_custom_condition', true ) ) {
// 特定の条件に基づいて異なる画像を表示
$new_image_url = 'path/to/alternate/image.jpg';
$html = '<img src="' . esc_url( $new_image_url ) . '" alt="条件付き画像" />';
}
return $html;
}
このコードは、特定のカスタムフィールドが存在する場合、異なる画像に変更します。
サンプルコード4: テンプレートを読み込む前にコンディションを判定する
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'conditional_thumbnail_render', 10, 2 );
function conditional_thumbnail_render( $html, $post_id ) {
if ( is_product() ) {
// 商品ページである場合のカスタマイズ
$html .= '<div class="product-condition">製品状態: 新品</div>';
}
return $html;
}
このコードは、商品ページのサムネイル画像の後に「製品状態: 新品」という状態を表示します。
サンプルコード5: レイアウト調整用の属性を追加
add_filter( 'woocommerce_single_product_image_thumbnail_html', 'add_custom_attributes', 10, 2 );
function add_custom_attributes( $html, $post_id ) {
return str_replace( 'src=', 'data-custom-color="blue" src=', $html );
}
このコードは、サムネイル画像にカスタムデータ属性を追加します。
この関数のアクションでの使用可能性
アクション | 使用例 |
---|---|
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 |
以上が、woocommerce_single_product_image_thumbnail_html
フィルタの詳細解説およびサンプルコードです。