从URL参数自动填充输入表单字段

从URL参数自动填充输入表单字段

问题描述:

I have a button on a woocommerce page (http://.../product/abcd/) that has a button "Book Appointments Now" that links to another page with form fields to submit (http://.../booking-appointments/?id=1238&sku=1) which has ProductID and SKU on the URL of that product from the previous page.

I want it to auto-populate the ProductID field automatically each time this page loads from the URL parameters.

Any help is appreciated.

我在woocommerce页面上有一个按钮( http://.../product/abcd/ code>)有一个“Book Nowointments Now”按钮,链接到另一个页面,并提交表单字段( http://.../booking-appointments/?id = 1238& sku = 1 代码>)在上一页的该产品的URL上有 ProductID code>和 SKU code>。 p>

我希望每次从URL参数加载此页面时,它都会自动填充 ProductID code>字段。 p>

感谢任何帮助。 p> div>

To auto populate the product ID and the product SKU in your booking form (page), you should try this (without any guaranty as it can be tested for real on your page form):

add_action( 'wp_footer', 'autopopulate_product_id_script' );
function autopopulate_product_id_script() {
    if( isset( $_GET['id'] ) ):
        ?>
        <script type="text/javascript">
        (function($){
            $('input[name="productid"]').val("<?php echo $_GET['id']; ?>");
            $('input[name="productsku"]').val("<?php echo $_GET['sku']; ?>");
        })(jQuery);
        </script>
        <?php
    endif;
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

The product id and the product sku need to be passed in url something like: http//www.example.com/booking-page/?id=124&&sku=AH1584

And your <imput> text fields should be something like:

<input type="text" name="productid" val="">
<input type="text" name="productsku" val="">

So for the product sku is something similar, that you will be able to add with ease…

But as javascript is already very active in you "Easy Appointments" booking form, I don't know if this will work.


This answer is related to: Add custom "Booking" button to WooCommerce Product single pages

You can pass the product ID and SKU in the URL and get it via $_GET. Then load it into the input field. Here's an example:

http://www.example.com/?product-id=123&sku=abcd456

Then use $_GET to get the URL parameters:

$productId = $_GET['product-id'];
$sku = $_GET['sku'];

Your input field would be like this:

<label for="product-id">Product ID:</label> <input type="text" name="product-id" id="product-id" value="<?php echo $productId; ?>" disabled>

I even added a disabled attribute to prevent the user/customer from editing the product ID. You can use PHP to secure it from the backend when the form gets submitted.