0

I want to add the list of my available contact forms (created in contact forms 7) to a dropdown in the customizer.

Here is the code I used:

function contact_form_list() {
    $args = array('post_type' => 'wpcf7_contact_form');
    $cf7forms = get_posts( $args );
    foreach($cf7forms as $cf7form) {
            return $cf7form->post_title;
    }
}

// Add setting and control for Contact section

$wp_customize->add_setting( 'contact_list', array(
    'transport' => 'postMessage'
));
$wp_customize->add_control( 'contact_list', array(
    'label'    => esc_html__( 'Contact form', 'mytheme' ),
    'type'     => 'select',
    'section'  => 'contact_section',
    'priority' => 4,
    'choices'  => contact_form_list()
));

It displays the dropdown but there is no choice. It is empty.

What am I doing wrong? Or is it the wrong way to do so?

Thanks for your help !

6

Ok I found it, here is the answer for next ones who are looking for the same thing:

$cf7forms_list = array();
$args = array('post_type' => 'wpcf7_contact_form');
$cf7forms = get_posts( $args ); 
foreach($cf7forms as $cf7form) {
    $cf7forms_list[$cf7form->post_title] = $cf7form->post_title;
}

$wp_customize->add_setting( 'contact_list_section', array(
    'transport' => 'postMessage'
));
$wp_customize->add_control( 'contact_list_section', array(
    'label'    => esc_html__( 'Contact form', 'mytheme' ),
    'type'     => 'select',
    'section'  => 'contact_section',
    'priority' => 4,
    'choices'  => $cf7forms_list,
));
1
  • In the event you want to return more than 5 though line 2 should be changed to "$args = array('post_type' => 'wpcf7_contact_form', 'posts_per_page' => 999); Otherwise get_posts will only give you back 5 posts and leave you scratching your head.
    – Mav2287
    Aug 6 '19 at 21:22

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.