【问题标题】:Defined product custom field value replace price on WooCommerce loopWooCommerce 循环中定义的产品自定义字段值替换价格
【发布时间】:2020-11-19 03:03:15
【问题描述】:

在我的 WooCommerce 产品上,我想用产品型号参考自定义字段替换产品价格(例如:#AB2568B)。如何显示型号参考而不是价格?请帮忙。

【问题讨论】:

  • 感谢回复我有产品,我有自定义型号或者您可以说产品的 ID,由我们决定我想显示产品型号而不是上图中显示的产品成本.....请检查图像它将帮助您理解link

标签: php wordpress woocommerce custom-fields price


【解决方案1】:

由于您没有提供有关产品自定义字段的任何详细信息,因此下面的代码将在管理单个产品设置中添加自定义字段。

那么当这个自定义字段有一个定义的值时,它就会代替产品价格:

// 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 文件中。经过测试并且可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2022-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多