Woocommerce 商店和存檔頁面上的產品影像輸出如下所示:
<img src="http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-300x300.jpg" class="attachment-woocommerce_thumbnail size-woocommerce_thumbnail" alt="" loading="lazy" srcset="http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-300x300.jpg 300w, http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-100x100.jpg 100w, http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-500x500.jpg 500w, http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-150x150.jpg 150w, http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2-768x768.jpg 768w, http://localhost/wp-content/uploads/2022/02/long-sleeve-tee-2.jpg 801w" sizes="(max-width: 300px) 100vw, 300px" width="300" height="300">
我想添加課程。我到處尋找我能想到的地方,但沒有運氣。
我嘗試使用 jQuery 添加類:
<script>
'use strict';
( function( $ ) {
<?php if (is_shop()): ?>
// Add classes to the img tag
$('.attachment-woocommerce_thumbnail').addClass('w-full md:h-96 sm:h-auto object-cover');
<?php else: ?>
$('.attachment-woocommerce_thumbnail').addClass('w-full object-cover 2md:h-96');
<?php endif ?>
} )(jQuery);
</script>
最初可以使用,但是我使用了其他人撰寫的無限滾動插件,并且當無限滾動插件加載更多影像時,它不會將類添加到新影像中。有什么建議嗎?
uj5u.com熱心網友回復:
您可以使用wp_get_attachment_image_attributesWordPress 過濾器鉤子,這將允許您通過添加所需的類$attr['class']
我添加了 3 個示例:
- 普通班
- 基于條件標簽
- 基于產品(ID)
所以你得到:
/**
* Filters the list of attachment image attributes.
*
* @since 2.8.0
*
* @param string[] $attr Array of attribute values for the image markup, keyed by attribute name.
* See wp_get_attachment_image().
* @param WP_Post $attachment Image attachment post.
* @param string|int[] $size Requested image size. Can be any registered image size name, or
* an array of width and height values in pixels (in that order).
*/
function filter_wp_get_attachment_image_attributes( $attr, $attachment, $size ) {
// 1. Add general class to the existing classes (use = versus .= to overwrite the existing classes)
$attr['class'] .= ' my-class';
// 2. Returns true when on the product archive page (shop).
if ( is_shop() ) {
// Add class
$attr['class'] .= ' my-class-shop';
} else {
// Add class
$attr['class'] .= ' my-class-not-shop';
}
// 3.1 Specific product ID
if ( $attachment->post_parent == 30 ) {
// Add class
$attr['class'] .= ' my-class-for-product-id-30';
}
// OR
// 3.2 Specific product ID
$product = wc_get_product( $attachment->post_parent );
// Is a WC product
if ( is_a( $product, 'WC_Product' ) ) {
if ( $product->get_id() == 815 ) {
// Add class
$attr['class'] .= ' my-class-for-product-id-815';
}
}
return $attr;
}
add_filter( 'wp_get_attachment_image_attributes', 'filter_wp_get_attachment_image_attributes', 10, 3 );
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/454866.html
