iakar
iakar

Reputation: 11

WordPress Contact Form 7 (CF7) plugin how to add data-attributes to select field options

I have a custom CF/ select field: [select* pcname]

I use this function to add the values to the field:

function thebox_add_cf7_select_product_list( $tag, $unused ) {  

    if ( $tag['name'] != 'pcname' ) {
        return $tag;  
    }

    $args = array ( 'post_type' => 'my_products',                      
                    'orderby' => 'title',  
                    'order' => 'ASC',
                    'posts_per_page' => -1
                );  
    $products = get_posts($args);  

    if ( ! $products )  
        return $tag;  

    foreach ( $products as $product ) {  

        $tag['raw_values'][] = $product->post_title;  
        $tag['values'][] = $product->post_title;  
        $tag['labels'][] = $product->post_title;  

    }  


    return $tag;  
}  
add_filter( 'wpcf7_form_tag', 'thebox_add_cf7_select_product_list', 10, 2);  

This works great. I get something like this as my output:

<select name="pcname" class="wpcf7-form-control wpcf7-select"">
<option value="Product A">Product A</option>
<option value="Product B">Product B</option>
<option value="Product C">Product C</option>
....
</select>

But now I need to add additional Informations to each option like the Product-ID and the Product-Main-Category. Therefore I want to use data-attributes, but I do not know how to add them in my wpcf7_form_tag function above? How is it possible to add data-attributes to the options of my select-field?

The output should look like this:

 <select name="pcname" class="wpcf7-form-control wpcf7-select"">
    <option value="Product A" data-id="1" data-cat="Category A">Product A</option>
    <option value="Product B" data-id="2" data-cat="Category B">Product B</option>
    <option value="Product C" data-id="3" data-cat="Category B">Product C</option>
    ....
 </select>

Upvotes: 1

Views: 2587

Answers (1)

Full Stop
Full Stop

Reputation: 853

Try with this CF7 filter code in functions.php

add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
    $str_pos = strpos( $content, 'name="unique-name"' ); //name='yourfield name'
    if ( $str_pos !== false ) {
        $content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
    }
    return $content;
}

Upvotes: 2

Related Questions