Home  >  Q&A  >  body text

Importance of Ajax add to cart button with custom fields on single product page

<p>I'm trying to edit the "Add to Cart" button for a single product page. Successfully added a custom ajax call using LoicTheAztec's solution. </p> <p>The code runs just fine. However, I need to change $product_id in the solution's code to the product's custom field value, which is "custom_id". </p> <p>Try to parse through the $custom_data variable, similar to: </p> <p><code>$cart_item_key = WC()->cart->add_to_cart( $custom_data['custom_id'], $quantity, $variation_id, $variation, $cart_item_data );</code>< ;/p> <p>Also tried using another function call: </p> <pre class="brush:php;toolbar:false;">function single_product_text_field() { global $product; // $cus_id = get_post_meta( $product->get_id(), 'custom_id', true ); $cus_id = $product->get_meta( 'custom_id' ); if ( ! empty($cus_id) ) return $cus_id; }</pre> <p>Unfortunately, I was unsuccessful. No ajax request is made on button click. If I replace $product_id with a static custom field value, it works fine. </p> <p>Unfortunately, I have no more ideas. If you have any ideas I would at least be grateful! </p>
P粉959676410P粉959676410437 days ago512

reply all(1)I'll reply

  • P粉362071992

    P粉3620719922023-09-02 10:20:20

    In my case the global $post page was already declared. so

    $cus_id = get_post_field('custom_id', $product_id);

    solved the problem!

    reply
    0
  • Cancelreply