通过Woocommerce中的钩子定制循环产品图像

时间:2018-06-09 11:34:17

标签: php wordpress image woocommerce hook-woocommerce

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

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

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

出现缩略图图像。 我很困惑<img src"" ....位置在哪里? 如何编辑该代码?

由于

2 个答案:

答案 0 :(得分:3)

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

    return $product ? $product->get_image( $image_size ) : '';
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。

  

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

答案 1 :(得分:1)

LoicTheAztec的答案非常好,但我认为它包含一个很小但很关键的错误。我们删除了标准输出(echo)钩子,并没有添加过滤器(它返回结果),而是添加了一个动作,因此,我们应该做echo。那个狡猾的/看不见的错误已经把我的时间吃光了。 :)

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