Validate custom shortcode
-
Hi guys,
I’ve created a custom shortcode that retrieves the title of a certain custom post type. These titles are placed in a select box.
I want to make sure that the user has selected one of these titles when filling in the form, so I guess some validation is needed. The official documentation about this doesn’t seem to be sufficient for me and I can’t find any useful topics that help me out.
Here I create the shortcode:
function upcoming_events($tag){ $tag = new WPCF7_Shortcode( $tag ); wp_reset_query(); $output = "<select id='locatie' name='locatie' class='wpcf7-form-control wpcf7-select form-control' onchange='document.getElementById(\"locatie\").value=this.value;'><option disabled selected value> -- selecteer een locatie -- </option>"; global $post; $locaties_args = array( 'post_type' => 'speeldata', 'posts_per_page' => -1, 'orderby' => 'name', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'date', 'value' => date("Y-m-d"), 'compare' => '>=', 'type' => 'DATE' ), ), ); $query = new WP_Query( $locaties_args ); while( $query->have_posts() ) : $query->the_post(); //var_dump($post); $atts = fw_get_db_post_option(get_the_id()); setlocale(LC_ALL, 'nl_NL'); $local_date = trim(strftime("%e %B %Y", strtotime($atts['datum']))); //var_dump($local_date); //var_dump($atts); $output .= "<option value='". $post->post_name ."'>". get_the_title() ." (". $local_date .")</option>"; endwhile; $output .= "</select>"; return $output; } function custom_add_shortcode() { wpcf7_add_shortcode('upcoming-events', 'upcoming_events', true); wpcf7_add_shortcode('upcoming-events*', 'upcoming_events', true); } add_action( 'wpcf7_init', 'custom_add_shortcode' );
This all works fine, the value is passed to the mail after the form gets submitted. The only problem is that I want the user to actively make a selection, so I need a default empty value and validation.
I got this so far, I know this is nowhere near the solution but when adding more code I the debug console throws 500 internal server errors at me.
function upcoming_events_validation( $result, $tag) { $tag = new WPCF7_Shortcode( $tag ); $result->invalidate( $tag, "Selecteer een locatie" ); return $result; } add_filter( 'wpcf7_validate_upcoming_events*', 'upcoming_events_validation');
- The topic ‘Validate custom shortcode’ is closed to new replies.