【问题标题】:Hook for customizing product image thumbnail用于自定义产品图像缩略图的挂钩
【发布时间】:2015-03-18 11:20:37
【问题描述】:

我需要 woo-commerce 方面的帮助来覆盖购物车产品图片缩略图。
我正在创建一个用于在详细信息页面中自定义产品的插件,如果我们“添加到购物车”,它将在购物车页面中使用自定义缩略图进行更新。

如果有任何钩子可用于覆盖图像,请告诉我。

【问题讨论】:

  • 您想要与缩略图相同的图像还是不同产品的不同图像?
  • 在购物车页面中只有我自定义的产品缩略图应该更改
  • 修正了一些拼写和格式。删除无关的谢谢。

标签: php wordpress woocommerce


【解决方案1】:

我也花了很多时间寻找答案,甚至问了一个 Stackoverflow 问题 (WooCommerce: change product image permalink with filter/action hook),现在恰好是重复的(在提交我自己的问题之前找不到这个问题)。

答案:

钩子是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' );

并且您的缩略图将被替换(如果您想单独更改每个缩略图,则需要进行更多处理)。

【讨论】:

    【解决方案2】:

    要更改 WooCommerce 购物车页面的缩略图大小,您需要执行以下步骤:

    1. function.php 创建你需要的尺寸:

      if ( function_exists( 'add_image_size' ) ) {
          add_image_size( 'custom-thumb', 100, 100, true ); // 100 wide and 100 high
      }
      
    2. cart.php里面应该定位到your_theme\woocommerce\cart\cart.php

      $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image( 'custom-thumb' ), $cart_item, $cart_item_key );
      

    【讨论】:

    • 多年与 WooCommerce 的合作教会我尽可能少地编辑核心模板。它会导致更多的工作进一步下线。使用操作/过滤器
    【解决方案3】:

    请查看 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 );
    

    【讨论】:

    • 你好 helgatheviking,谢谢你的回复。我已经看到了这个东西,但我需要用购物车图像覆盖我的自定义图像。这意味着我必须从我的自定义插件中进行更新选项。我没有想要自定义我想要覆盖。我需要一个钩子来执行此操作。
    • 对不起,我不明白。如果要覆盖购物车图像,请使用此钩子。如果这不是您想要做的,请再次解释。
    • PS- 我会在自己的时间检查 stackoverflow,并在我喜欢时回复。如果您准备雇用我,请只给我发电子邮件。
    【解决方案4】:

    将“中等”更改为您所需的图像尺寸:

    /**
     * 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 模板文件。

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-05-21
      • 2020-11-22
      • 2021-11-10
      • 2013-06-22
      • 2011-10-16
      • 2021-12-03
      • 2018-11-19
      • 1970-01-01
      相关资源
      最近更新 更多