cart/cart.php 模板文件包含(第 65-75 行)
<td class="product-thumbnail">
<?php
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
if ( ! $product_permalink ) {
echo $thumbnail; // PHPCS: XSS ok.
} else {
printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
}
?>
</td>
这确保缩略图与相关 HTML 代码的输出
woocommerce_cart_item_thumbnail过滤钩子,第一个参数包含$_product->get_image()
然后引导我们进入下一个代码
/**
* Returns the main product image.
*
* @param string $size (default: 'woocommerce_thumbnail').
* @param array $attr Image attributes.
* @param bool $placeholder True to return $placeholder if no image is found, or false to return an empty string.
* @return string
*/
public function get_image( $size = 'woocommerce_thumbnail', $attr = array(), $placeholder = true ) {
$image = '';
if ( $this->get_image_id() ) {
$image = wp_get_attachment_image( $this->get_image_id(), $size, false, $attr );
} elseif ( $this->get_parent_id() ) {
$parent_product = wc_get_product( $this->get_parent_id() );
if ( $parent_product ) {
$image = $parent_product->get_image( $size, $attr, $placeholder );
}
}
if ( ! $image && $placeholder ) {
$image = wc_placeholder_img( $size, $attr );
}
return apply_filters( 'woocommerce_product_get_image', $image, $this, $size, $attr, $placeholder, $image );
}
依次调用其他函数。
但是,因为您想保持产品缩略图完整并用 span 标签包裹,您可以只使用。
function filter_woocommerce_cart_item_thumbnail( $product_image, $cart_item, $cart_item_key ) {
// Wrap the thumbnail in a span
$product_image = '<span>' . $product_image . '</span>';
return $product_image;
}
add_filter( 'woocommerce_cart_item_thumbnail', 'filter_woocommerce_cart_item_thumbnail', 10, 3 );
注意:如果要更改元素中的某些内容,可以使用str_replace PHP 函数
喜欢:
$image = '<img src="myimage.jpg" width="500" height="600">';
之前的结果:
<img src="myimage.jpg" width="500" height="600">
与str_replace:
// Replace <img with <span><img
$image = str_replace( '<img', '<span><img', $image );
之后的结果:
<span><img src="myimage.jpg" width="500" height="600">
另一种选择是覆盖模板文件(请参阅您已经提到的有关如何应用的答案),因此结合该答案将
if ( ! $product_permalink ) {
echo $thumbnail; // PHPCS: XSS ok.
} else {
printf( '<a href="%s">%s</a>', esc_url( $product_permalink ), $thumbnail ); // PHPCS: XSS ok.
}
成为
echo '<span>' . $thumbnail . '</span>';