简体   繁体   中英

How to send form data to woocommerce add_to_cart from custom template?

I have a created a new template inside theme's folder named Pre-Checkout Customer Details where there is a form. and the page looks like:

    <?php /* Template Name: Pre-Checkout Customer Details */ ?>
<?php


if ( ! defined( 'ABSPATH' ) ) {

    exit; // Exit if accessed directly.
}

get_header(); ?>

<form action="/checkout/?">
    <input type="name" name="name">
    <input type="date" name="start_date">
    <input type="submit" name="Next">
</form>

<?php get_footer(); ?>

Along with that, this page's URL will always contain some parameters such as

?add-to-cart=608&subscribe='weight_loss_plan'

which will look somewhat:

https://challengecenter-q8.com/pre-checkout-customer-details/?add-to-cart=608&subscribe=%D8%A8%D9%86%D8%A7%D8%A1%20%D8%B9%D8%B6%D9%84%20%D8%A3%D8%B4%D8%AA%D8%B1%D8%A7%D9%83%20%D8%A7%D8%B3%D8%A8%D9%88%D8%B9%D9%8A%D9%86%20%D9%88%D8%AC%D8%A8%D8%AA%D9%8A%D9%86

Now when I am clicking on submit, it is showing page not found instead of moving to the cart page. Also, I want the form details to show on the checkout page like: https://challengecenter-q8.com/checkout/?name='value 1'&date='04-04-2021'

How can I achieve that?

Thank you in advance!

Note: “Enable AJAX add to cart buttons on archives” is enabled and “Redirect to the cart page after successful addition”. is disabled.

I would look into using actions to accomplish what you're trying to do. You can use the template_redirect action to check for your URL parameter and programmatically add that item to the cart then redirect to which ever page you would like.

You can simply create an anchor link for the page you're currently on that has the parameter you're needing (in my case 'atc').

Here's a piece of code I use to do this.

add_action('template_redirect', 'mks_add_to_cart');
function mks_add_to_cart(){
  $pid = filter_input( INPUT_GET, 'atc', FILTER_VALIDATE_INT );
  if( !empty( $pid ) ) {
    global $woocommerce;
    $woocommerce->cart->add_to_cart( $pid );
    
    wp_redirect( site_url() . '/cart' );
    exit;
  }}

Use another action for your second part to display on the checkout page. I use Business Bloomer Visual Hook Guide often to reference where I want information to show.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM