Problem: I have a CRED Commerce form that allows Users to pay a fee and create a post. In some cases, the fee is not required. I would like to use a checkbox in the form to indicate whether or not the fee should be charged. If the checkbox is not checked, the User should not be charged, but the post should still be created. If the checkbox is checked, the User should have the fee product added to their cart with CRED Commerce, and the payment workflow in CRED Commerce should be followed normally.
Solution:
- Set up this form to always add the registration product to the User's cart, regardless of any input. We will override this with code when needed.
- Replace the generic radio control with a generic checkbox like this:
[cred_generic_field field='addfee' type='checkbox' class='' urlparam=''] { "required":0, "validate_format":0, "checked":0, "default":"1", "label":"Add Handling Fee" } [/cred_generic_field]
- Add the following custom code to your child theme's functions.php file:
add_action( 'cred_commerce_before_add_to_cart', 'ts_only_buy_if_checked', 10, 2 ); function ts_only_buy_if_checked( $form_id, $post_id ) { $forms = array( 123, 456 ); if( in_array( $form_id, $forms) ) { if( !isset( $_POST['addfee'] ) || $_POST['addfee'] != 1 ) { wp_redirect( 'http://yoursite.com/somepage' ); exit(); } } }
Replace 123, 456 with a comma-separated list of any CRED form IDs where you want to apply this modification. Change the URL to redirect the User to some other destination on your site. You have access to the ID of the post that was added or edited in the $post_id variable. Now if the checkbox is not checked, the User will be redirected without placing the item in their cart.
You can call get_permalink using the $post_id parameter in your callback to redirect to the post that was created by CRED. Here is the updated redirect code:
... wp_redirect( get_permalink( $post_id ) ); ...
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-commerce-api/#cred_commerce_before_add_to_cart
https://developer.wordpress.org/reference/functions/wp_redirect/
https://developer.wordpress.org/reference/functions/get_permalink/
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
Sun | Mon | Tue | Wed | Thu | Fri | Sat |
---|---|---|---|---|---|---|
8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | 8:00 – 12:00 | - | - |
13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | 13:00 – 17:00 | - | - |
Supporter timezone: America/New_York (GMT-04:00)
This topic contains 7 replies, has 3 voices.
Last updated by 6 years, 10 months ago.
Assisted by: Christian Cox.