好的,所以我想通了...
在我的树枝文件中,我调用了一个函数{% 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> $' . $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> $' . $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;
}
最终需要做更多的工作,因为我必须处理可变价格的产品以及那些有折扣但没有可变价格的产品的折扣等,但最终这意味着树枝模板中没有任何功能,这是最好的结果。
希望我可以标记所有我签出的堆栈溢出帖子,但找不到它们。如果这对其他人有帮助,那就太好了!