【问题标题】:Customizing loop product image via a hook in Woocommerce通过 Woocommerce 中的钩子自定义循环产品图像
【发布时间】:2018-11-19 07:03:37
【问题描述】:

我正在自定义 woocommerce 主题。 我使用钩子动作 woocommerce 坚持使用循环产品。

要在循环中调用/包含缩略图,我们称之为钩子

<?php do_action('woocommerce_before_shop_loop_item_title'); ?>

然后出现缩略图。 我很困惑&lt;img src"" .... 的位置在哪里? 如何编辑该代码?

谢谢

【问题讨论】:

    标签: php wordpress image woocommerce hook-woocommerce


    【解决方案1】:

    钩子woocommerce_before_shop_loop_item_titlethis function code加载图片:

    if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
    
        /**
         * Get the product thumbnail for the loop.
         */
        function woocommerce_template_loop_product_thumbnail() {
            echo woocommerce_get_product_thumbnail(); // WPCS: XSS ok.
        }
    }
    

    所以你可以看到它使用woocommerce_get_product_thumbnail() function

    if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {
    
        /**
         * Get the product thumbnail, or the placeholder if not set.
         *
         * @param string $size (default: 'woocommerce_thumbnail').
         * @param int    $deprecated1 Deprecated since WooCommerce 2.0 (default: 0).
         * @param int    $deprecated2 Deprecated since WooCommerce 2.0 (default: 0).
         * @return string
         */
        function woocommerce_get_product_thumbnail( $size = 'woocommerce_thumbnail', $deprecated1 = 0, $deprecated2 = 0 ) {
            global $product;
    
            $image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
    
            return $product ? $product->get_image( $image_size ) : '';
        }
    }
    

    我希望这能回答您的问题,并消除您的困惑。


    自定义循环产品图片

    现在,你可以从钩子中移除这个默认函数来添加你自己的自定义函数,使用这个:

    remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
    add_action( 'woocommerce_before_shop_loop_item_title', 'custom_loop_product_thumbnail', 10 );
    function custom_loop_product_thumbnail() {
        global $product;
        $size = 'woocommerce_thumbnail';
    
        $image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
    
        echo $product ? $product->get_image( $image_size ) : '';
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    所以现在你只需要自定义函数内部的代码……

    【讨论】:

    • 非常感谢,你拯救了我的夜晚 :) @loic
    【解决方案2】:

    LoicTheAztec 的答案非常好,但我认为它包含一个小而严重的错误。我们删除了标准输出 (echo) 钩子,添加的不是过滤器(它返回结果),而是一个动作,所以,我们应该做 echo。那个巧妙/不可见的错误占用了我足够的时间。 :)

    // there is
    return $product ? $product->get_image( $image_size ) : '';
    // should be
    echo $product ? $product->get_image( $image_size ) : '';
    

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 1970-01-01
      • 2021-03-04
      • 1970-01-01
      • 2021-07-01
      • 2021-01-09
      • 2020-07-21
      • 2020-05-21
      • 1970-01-01
      相关资源
      最近更新 更多