0

在我的 php 文件中,我可以编写以下内容:

$product = wc_get_product( $context['post']->ID );
$context['sale_price'] = $product->get_variation_sale_price( 'min', false );

{{sale_price}}在我的树枝文件中输出销售价格

但是我需要通过产品循环执行此操作。在我的树枝文件中,我可以运行该wc_get_product()功能{% set product = fn('wc_get_product',post.id) %}

但我怎么能做这样的事情:product->get_variation_sale_price( 'min', false )???

所以本质上是在前一个函数的一些输出上运行另一个函数。

谢谢!!!

4

1 回答 1

0

好的,所以我想通了...

在我的树枝文件中,我调用了一个函数{% set pricefield = function(['StarterSite', 'my_function'], post.ID) %},当我从下面的函数返回一个数组时,我有这两位输出:{% if pricefield.sale == 'true' %}<div class="ribbon">Sale</div>{% endif %}{{pricefield.price}}

在我的函数文件中,我有这个:

function my_function($i) {
        $product = wc_get_product($i);
        if ( $product->is_type( 'variable' ) ) :

            $product_variations = $product->get_available_variations();

            #2 Get one variation id of a product
            $variation_product_id = $product_variations [0]['variation_id'];

            #3 Create the product object
            $variation_product = new WC_Product_Variation( $variation_product_id );

            #4 Use the variation product object to get the variation prices
            if ($variation_product->sale_price) :
                return array('sale' => 'true', 'price' => '<del>$' . $variation_product->regular_price . '</del> &nbsp;$' . $product->get_variation_sale_price( 'min', false ));
            else : return array('sale' => 'false', 'price' =>  '$' . $variation_product->regular_price);
            endif;
        else:
            if ($product->sale_price) :
                return array('sale' => 'true', 'price' => '<del>$' . $product->regular_price . '</del> &nbsp;$' . $product->sale_price);
            else : return array('sale' => 'false', 'price' =>  '$' . $product->regular_price);
            endif;
        endif;
    }

    /** This is where you can add your own functions to twig.
     *
     * @param string $twig get extension.
     */
    public function add_to_twig( $twig ) {
        $twig->addExtension( new Twig_Extension_StringLoader() );
        $twig->addFilter( new Twig_SimpleFilter( 'myfoo', array( $this, 'myfoo' ) ) );
        $twig->addFunction( new Timber\Twig_Function( 'my_function', 'my_function' ) );
        return $twig;
    }

最终需要做更多的工作,因为我必须处理可变价格的产品以及那些有折扣但没有可变价格的产品的折扣等,但最终这意味着树枝模板中没有任何功能,这是最好的结果。

希望我可以标记所有我签出的堆栈溢出帖子,但找不到它们。如果这对其他人有帮助,那就太好了!

于 2019-09-13T11:57:48.190 回答