How to add options to select field from php array to Contact form 7 WordPress

I have an one-page site in wordpress. I need to put information from php array $cat_good in two select box. It works ok in index.php file like this:

<div>
    <select id="flowers_type" class="styled">
        <option value="">--</option>
        <?php 
            foreach ( $cat_good as $key => $value) {
                echo '<option value="' . $key . '">' . $key . '</option>';
            } 
        ?>
    </select>
</div>
<div>
    <select id="flowers_type_item" class="styled">
        <option value="">--</option>
        <?php 
            foreach ( $cat_good as $key => $value) {
                $good = $key;
                foreach ( $value as $key => $value ) {
                    echo '<option class="' . $good . '" value="' . $key . '">' . $value . '</option>'; 
                }
            } 
        ?> 
    </select>
</div>

The question is, how to put these two select box to contact form 7?

Read More

With help of Dhanuka Nuwan now I have the code in function.php, which helps me to add selectors to contact form 7.

function flowers_type(){<!-- here is my code for $cat_good -->
$output .= "<div><select name='flowers_type' id='flowers_1' class='styled'><option value='0'>--</option>";      
    foreach ( $cat_good as $key => $value) {
        $output .= "<option value='$key'>$key</option>";         
     }
$output .= "</select></div>";
$output .= "<div><select name='flowers_type_item' id='flowers_2' class='styled'><option value='0'>--</option>";     
    foreach ( $cat_good as $key => $value) {
        $good = $key;
        foreach ( $value as $key => $value ) {
            $output .= "<option class='$good' value='$key'>$value</option>";
        }
     }
     $output .= "</select></div>";
     return $output;}

But also I need the second selector to be depended from the first. I’m trying to do this with help https://github.com/tuupola/jquery_chained. In my js file I have:

$("#flowers_2").chained("#flowers_1");

Unfortunately, it doesn’t work.

Related posts

Leave a Reply

1 comment

  1. You can add a shortcode to contact form 7 using wpcf7_add_shortcode easily. Here is your code.

    function flowers_type(){
       $output = "<select name='flowers_type' id='flowers_type' onchange='document.getElementById("flowers_type").value=this.value;'><option value="">--</option>";
       foreach ( $cat_good as $key => $value) {
                $output .= "<option value='$key'> $key </option>";
            } 
    
       $output .= "</select>";
    return $output;
    }
    
    wpcf7_add_shortcode('flowers_type', 'flowers_type', true);
    

    now you can use [flowers_type] shortcode inside your contact form 7 form.Please note this code is not tested. backup your files before use. do the same thing to your other one.

    Have fun. 🙂