由于您没有提供产品自定义字段的任何详细信息,下面的代码将添加一个自定义设置字段来管理单个产品页面。
然后,当此自定义字段具有定义的值时,它将替换产品价格:
// Admin product general settings: Display a custom field (below prices)
add_action( 'woocommerce_product_options_pricing', 'add_product_general_setting_field' );
function add_product_general_setting_field() {
echo '<div class="options_group">';
woocommerce_wp_text_input( array(
'id' => '_reference_id',
'label' => __( 'Reference Id', 'woocommerce' ),
'placeholder' => __( 'Please enter the model reference Id', 'woocommerce' ),
'description' => __( 'Please enter the model reference Id', 'woocommerce' ),
) );
echo '</div>';
}
// Admin product general settings: Save custom field
add_action( 'woocommerce_admin_process_product_object', 'save_product_general_setting_field' );
function save_product_general_setting_field( $product ){
if(isset($_POST['_reference_id']) ) {
$product->update_meta_data( '_reference_id', sanitize_texT_field( $_POST['_reference_id']) );
}
}
// replace loop product price by the model reference Id
add_action( 'woocommerce_after_shop_loop_item_title', 'action_after_shop_loop_item_title_callback', 9 );
function action_after_shop_loop_item_title_callback() {
global $product;
$reference_id = $product->get_meta('_reference_id');
if( ! empty($reference_id) ) {
remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 ); // remove the price
// Display the model reference
echo '<span class="price regerence_id">'.$reference_id.'</span>';
}
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。