我需要一个关于woo-commerce的帮助来覆盖购物车产品图像缩略图
我正在创建一个插件,用于在详细信息页面中自定义产品,如果我们"添加到购物车",它将在购物车页面中更新为自定义缩略图。
如果有任何钩子可用于覆盖图像,请告诉我。
我也花了很多小时寻找答案,甚至问了一个Stackoverflow问题(WooCommerce:用过滤器/操作挂钩更改产品图像永久链接),现在恰好是重复的(在提交自己的问题之前找不到这个问题)
答案:
挂钩为woocommerce_cart_item_thumbnail
。因此,在您的functions.php
中添加
function custom_new_product_image($a) {
$class = 'attachment-shop_thumbnail wp-post-image'; // Default cart thumbnail class.
$src = [PATH_TO_YOUR_NEW_IMAGE];
// Construct your img tag.
$a = '<img';
$a .= ' src="' . $src . '"';
$a .= ' class="' . $class . '"';
$a .= ' />';
// Output.
return $a;
}
add_filter( 'woocommerce_cart_item_thumbnail', 'custom_new_product_image' );
并且您的缩略图将被替换(如果您想单独更改每个缩略图,则需要更多的处理)。
要更改WooCommerce购物车页面的缩略图大小,您需要下一步:
-
在
function.php
中创建您需要的大小:if ( function_exists( 'add_image_size' ) ) { add_image_size( 'custom-thumb', 100, 100, true ); // 100 wide and 100 high }
-
在应该位于
your_theme'woocommerce'cart'cart.php
中的cart.php
中找到$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image( 'custom-thumb' ), $cart_item, $cart_item_key );
请查看woocommerce/templates/cart/cart.php
中的WooCommerce购物车模板。
购物车中的产品缩略图有一个清晰的过滤器woocommerce_cart_item_thumbnail
。
$thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key );
为您所需的图像大小更改"介质":
/**
* Update cart product thumbnail
*/
function woocommerce_cart_item_thumbnail_2912067($image, $cartItem, $cartItemKey)
{
$id = ($cartItem['variation_id'] !== 0 ? $cartItem['variation_id'] : $cartItem['product_id']);
return wp_get_attachment_image(get_post_thumbnail_id((int) $id), 'medium');
}
add_filter('woocommerce_cart_item_thumbnail', 'woocommerce_cart_item_thumbnail_2912067', 10, 3);
这导致您不必更新WooCommerce的核心模板文件。