Last active
October 1, 2023 22:12
-
-
Save Acephalia/624b5705e14c8326c053d3a8ed515f76 to your computer and use it in GitHub Desktop.
WC Product Dropdown List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Product Dropdown Form by u/acephaliax | |
//This snippet will add a shortcode [[product-dropdown] that can be used to display a list of store products in a dropdown form. On submission the product will be added to cart and directed to the cart page. | |
//Use CSS selectors to style form as needed. | |
// Add shortcode for the product dropdown form | |
function product_dropdown_shortcode() { | |
ob_start(); | |
?> | |
<div class="product-dropdown-container"> | |
<form action="" method="POST" class="product-dropdown-form"> | |
<?php | |
// Get all products | |
$products = wc_get_products(array('status' => 'publish')); | |
if (!empty($products)) { | |
echo '<div class="product-dropdown-select">'; | |
echo '<select name="product_id">'; | |
foreach ($products as $product) { | |
echo '<option value="' . esc_attr($product->get_id()) . '">' . esc_html($product->get_name()) . '</option>'; | |
} | |
echo '</select>'; | |
echo '</div>'; | |
echo '<div class="product-dropdown-button">'; | |
echo '<input type="submit" name="buy_now" value="Buy Now" class="buy-now-button">'; | |
echo '</div>'; | |
} else { | |
echo '<p>No products found.</p>'; | |
} | |
?> | |
</form> | |
</div> | |
<script> | |
jQuery(function ($) { | |
$('.product-dropdown-form').on('submit', function (e) { | |
e.preventDefault(); | |
var product_id = $(this).find('select[name="product_id"]').val(); | |
if (product_id) { | |
// Add the selected product to the cart | |
$.post("<?php echo wc_get_cart_url(); ?>", { 'add-to-cart': product_id }, function () { | |
// Redirect to the cart page | |
window.location = "<?php echo wc_get_cart_url(); ?>"; | |
}); | |
} | |
}); | |
}); | |
</script> | |
<?php | |
return ob_get_clean(); | |
} | |
add_shortcode('product-dropdown', 'product_dropdown_shortcode'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment