Я хочу отображать обычную цену, рассчитанную на основе процента в настраиваемом поле, как событие по нажатию клавиши в woocommerce - PullRequest
1 голос
/ 14 июля 2020

Итак, я сначала создал 2 поля: настраиваемое поле для отображения рассчитанной цены и скрытое поле с процентным значением

/*Custom price field - to create custom field for simple product*/
add_action( 'woocommerce_product_options_pricing', 'wc_cost_product_field' );
function wc_cost_product_field() {
    woocommerce_wp_text_input( 
        array( 
            'id' => 'cost_price',
            'name' =>'cost_price',
            'class' => 'wc_input_price short', 
            'desc_tip'    => 'true',
            'description' => __( 'Your Profit price is calculated as ((Vendor price x 15%) + 500 + vendor price )', 'woocommerce' ),
            'label' => __( 'Total Price with Profit', 'woocommerce' ) . ' (' . get_woocommerce_currency_symbol() . ')' 
        ) 
    );
    
    woocommerce_wp_hidden_input(
    array( 
        'id'    => '_hidden_field[' . $post->ID . ']', 
        'name' => 'per',
        'value' => 0.15
        )
    );
}

Итак, я сохранил настраиваемое поле, чтобы всегда отображать

/*Custom price field - to save custom field for simple product*/
add_action( 'save_post', 'wc_cost_save_product' );
function wc_cost_save_product( $product_id ) {

     // stop the quick edit interferring as this will stop it saving properly, when a user uses quick edit feature
     if (wp_verify_nonce($_POST['_inline_edit'], 'inlineeditnonce'))
        return;

    // If this is a auto save do nothing, we only save when update button is clicked
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;
    if ( isset( $_POST['cost_price'] ) ) {
        if ( is_numeric( $_POST['cost_price'] ) )
            update_post_meta( $product_id, 'cost_price', $_POST['cost_price'] );
    } else delete_post_meta( $product_id, 'cost_price' );
    
    $hidden = $_POST['_hidden_field'][ $post_id ];
    if( ! empty( $hidden ) ) {
        update_post_meta( $post_id, '_hidden_field', esc_attr( $hidden ) );
    }
}

?>

Затем я добавил скрипт, который будет вызывать и запускать значение, а затем отображать его в настраиваемом поле

<script>
    const calculateprofit_price = (profitPrice, percent) => {
        profitPrice = parseFloat(profitPrice);
        percent  = parseFloat(pecent);
        return ((profitPrice * percent) + 500 + profitPrice).toFixed(2); // profit price
    }
    const $price = $('input[name="_regular_price"]'),
        $per = $('input[name="per"]'), 
        $profit_price = $('input[name="cost_price"]'); 
            
    $price.add( $per ).on('input', () => { // price and percent inputs events
    let profit_price = $price.val();              // Default to profit price
    if ( $per.val().length ) {          // if value is entered- calculate profit_price
        profit_price = calculateprofit_price($price.val(), $per.val());
    }
    $profit_price.val( profit_price );
    });
    
    $price.trigger('input');
    
</script>

Я проверил онлайн, чтобы увидеть доступные коды, чтобы помочь, но безрезультатно, пожалуйста, помогите. Это изображение того, чего я пытаюсь достичь , отображая рассчитанную обычную цену в настраиваемом поле

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...