I am trying to create a simple shortcode which allows me to display on a page a dropdown list and based on the chosen option it should display a specific contact form.

The shortcode on the backend: [formularze form="561,559,560" name="Form 1, Form 2, Form 3"] The "form" attribute is the contact form 7 ID, the "name" attribute is a name for a dropdown list.

The code:

function formularze_func( $atts ) {
$a = shortcode_atts( array(
    'form' => '',
    'name' => '',
), $atts );

$form = $a['form'];
$name = $a['name'];

$ids_array = explode(',', $form);
$names_array = explode(',', $name);

$dropdown = "<select id=\"selectForm\">";
for($i=0;$i<count($ids_array);$i++) {
    $dropdown .= "<option value=\"";
    $dropdown .= $i;
    $dropdown .= "\">";
    $dropdown .= $names_array[$i];
    $dropdown .= "</option>";    
$dropdown .= "</select>";

$formDiv = "<div id=\"form\"></div>";

$formDisplay = "
        var dropdown = document.getElementById(\"selectForm\");
        var value = dropdown.options[dropdown.selectedIndex].value;
        var formId = " . json_encode($ids_array(\\\\TOTALLY STUCK HERE\\\\)) . "
        document.getElementById(\"form\").innerHTML = \"[contact-form-7 id=\"formId\"]\";


$ready = $dropdown . $formDiv . $formDisplay;

if( count($ids_array) == count($names_array) ) {
    return $ready;
} else return "Error.";
add_shortcode( 'formularze', 'formularze_func' );

The code isn't maybe the prettiest in the world so I would be glad for any improvement.

The problem is in this place - \\TOTALLY STUCK HERE\\ How can I pass there the JS variable value?


You can't add logic for changing in that way. You need react on user "front-end" event with js.

Also this construction will work wrong:

 document.getElementById(\"form\").innerHTML = \"[contact-form-7 id=\"formId\"]\";

Will be always print [contact-form-7 id=\"formId\"], because js can't do_shortcode function itself.

If you wanna make it simple(without ajax process) you need:

1) Print all forms with php and style "display: none;"

2) Add onchange event for select

3) On change options "show" needed form

Quick example how print forms:

 $formDivs = '';
    forearch($ids_array as $i=>$id) {
      $formDivs .= do_shortcode("<div id=\"form_{$i}\" style="display: none;">[contact-form-7 id=\"{$id}\"]</div>");
  • Hi, thank you very much. It seems easier than my first thought, however, I can't get it working :( The JS code seems to fail, because the dropdown doesn't react at all. Here's the codepen, I hope you don;t mind: codepen.io/dandy7/pen/LLXwPK
    – Dandy
    Jul 11 '17 at 11:05
  • I make fork with fix for you! Check it please codepen.io/flinius/pen/weQVoq Jul 11 '17 at 11:31
  • Also add please logic for make invisible all others form onchange :) Jul 11 '17 at 11:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.