I have a hidden input form,which has my custom product price. I want each time i add new item to cart this price(form) which is dynamicly generated with javascript to be sent to functions.php using $_POST

Code :


<input id="hiddenfield" type="hidden" action="functions.php" value="foo" 
     name="hiddenfields" />

        <?php echo do_shortcode('[add_to_cart id="212"]');   ?>


function totalprice(){

var one=Number(document.getElementById("vol1").value);
var two=Number(document.getElementById("vol2").value);
var three=Number(document.getElementById("vol3").value);
var four=Number(document.getElementById("vol4").value);

var total=one+two+three+four;

var target=document.getElementById("final");

target.innerHTML=total +"€ VDC/ month";


 , 99 );

function woocommerce_pj_update_price()  {
$custom_price = 100;   
$target_product_id = 212;

    foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
        if($cart_item['data']->get_id() == $target_product_id){





The answer is AJAX. Each time the totals are calculated, send the form data to the wp ajax handler.

Step 1: pass your ajax URL from PHP to javascript using wp_localize_script just after you enqueue your script file.

wp_enqueue_script('myScript', 'my/script/path.js');
wp_localize_script('myScript', 'php_params', ['ajaxurl'=>admin_url('admin-ajax.php')]);

Step 2: make the AJAX call in your script.

    type: "POST",
    url: php_params.ajaxurl,
    data: {
    success: function(data){
        // do something
    error: function(errorThrown){
        // do something

Step 3: add the ajax method to your functions.php file

add_action( 'wp_ajax_nopriv_mytag_function_name', 'mytag_function_name' );
add_action( 'wp_ajax_mytag_function_name', 'mytag_function_name' );

function mytag_function_name(){
    // do something with your $_POST data
    $post = filter_input_array(INPUT_POST);
    echo "Here's my result to get returned to Javascript";

Learn more about AJAX in the WordPress Codex: https://codex.wordpress.org/AJAX

Hope this helps :)

| improve this answer | |
  • Thanks for the reply, i just noticed that each time something is added to cart the old price is getting overwritten too. For example: Added to cart product 1 with price 100 Added to cart product 1 with price 200 first price (100) becomes 200 too How can i fix this? – Dimitris HD Apr 3 '18 at 11:53
  • In your foreach loop you are setting the price of each item to $custom_price. You declared $custom_price outside of the loop so this is why all your cart items end up with the same price. Try moving your $custom_price calculation inside of the foreach loop so it's calculated for each item. – dawoodman71 Apr 10 '18 at 15:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.