Problem: I have a CRED form that includes an optional image field. If the User submits the form without including an image in the field, I would like to automatically choose 1 of 4 placeholder default images at random.
Solution:
Add this custom code to your child theme's functions.php file:
add_action('cred_save_data', 'cred_add_default_img_action',10,2); function cred_add_default_img_action($post_id, $form_data) { $forms = array( 1234, 5678 ); // if a specific form if (in_array($form_data['id'], $forms)) { if (!isset($_POST['wpcf-slug'])) { $pics = array( "http://yoursite.com/path/to/image1.jpg", "http://yoursite.com/path/to/image2.jpg", "http://yoursite.com/path/to/image3.jpg", "http://yoursite.com/path/to/image4.jpg", ); add_post_meta( $post_id, 'wpcf-slug', $pics[ rand( 0,3 ) ] ); } } }
Replace 1234, 5678 with a comma-separated list of CRED form IDs where you want to apply this code. Replace 'wpcf-slug' with your field slug, and add the 'wpcf-' prefix, replace the 4 URLs with the actual image URLs on your site. If you choose not to use 4 options, replace the '3' in 0,3 with a number one less than the number of default options.
Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_save_data
http://php.net/manual/en/function.rand.php
http://php.net/manual/en/language.types.array.php
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 4 replies, has 2 voices.
Last updated by 6 years, 9 months ago.
Assisted by: Christian Cox.