我之前的一个问题was answered并包含两个单独的函数,一个使用WooCommerce add_action
钩子 . 如何将此答案转换为我可以添加到产品页面的 shortcode ?
我正在使用页面构建器(Divi Builder)来创建WooCommerce产品页面的自定义布局/模板 . 使用短代码可以将短代码粘贴到构建器中,并将结果输出到该模板结构中的任何位置 .
这是我需要变成短代码的代码:
// Utility funtion: getting and formtting product data
function format_product_data_output( $the_id ){
$empty = __( '<em>(empty)</em>', 'woocommerce' );
// Get an instance of the WC_Product_Variation object
$product = wc_get_product( $the_id );
// Only wc_get_price_to_display() respect if product is to be displayed with or without including taxes
$price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ) );
$sale_price = wc_get_price_to_display( $product, array( 'price' => $product->get_sale_price() ) );
$sale_price = ! empty( $sale_price ) ? wc_price($sale_price) : $empty;
$size = $product->get_attribute( 'pa_size' );
$size = ! empty( $size ) ? get_term_by( 'slug', $size, 'pa_size' )->name : $empty;
$stock_qty = $product->get_stock_quantity();
$stock_qty = ! empty( $stock_qty ) ? $stock_qty : $empty;
$output = '
<ul>
<li class="fs-data-price">'.$price.'</li>
<li class="fs-data-size">Size: '.$size.'</li>
<li class="fs-data-sale">'.$sale_price.' Preferred Customer Price</li>
<li class="fs-data-stock">Quantity in Stock: '.$stock_qty.'</li>
</ul>';
return $output;
}
//
add_action( 'woocommerce_after_single_product', 'custom_table_after_single_product' );
function custom_table_after_single_product(){
global $product;
$output = '<div class="fs-product-data-wrapper">';
// Variable products
if( $product->is_type('variable'))
{
// Get available variations in the variable product
$available_variations = $product->get_available_variations();
if( count($available_variations) > 0 ){
foreach( $available_variations as $variation )
$output .= format_product_data_output( $variation['variation_id'] );
}
}
// Simple products
elseif( $product->is_type('simple'))
{
$output .= format_product_data_output( $product->get_id() );
}
else return; // Exit
echo $output .= '</div>'; // Display
}
2 回答
Update 2: 请尝试以下方法:
代码位于活动子主题(或活动主题)的function.php文件中 . 经过测试和工作 .
SHORTCODE USAGE:
在产品页面中:
[variation_table]
(无需任何定义ID)定义产品ID的位置:
[variation_table id='27']
您将需要使用Wordpress Shortcode Api
实现将是这样的:
我添加了add_shortcode行,
解释是短代码'format'执行'format_product_data_output'功能 .