0

I have a client using some third party forms that I want to easily drop in places on their site.

To easily update them site-wide I thought I would create an ACF repeater field on an options page with fields for form_id and form_markup that I could use to build the shortcode. The idea being a user could enter just the id of the form in the shortcode and the form would output.

i.e. [form form_id="1"]

The question is: how do I call the proper ID from the array of data? Here's where I started:

function form_shortcode( $atts ) {

    // Attributes
    shortcode_atts(
        array(
            'form_id'   => '',
        ), $atts
    )

    $forms = get_field( 'forms', 'option' );
    foreach ( $forms as $form ) {
        $form_id = get_sub_field( 'form_id', 'option' );
    }

    return $form_id;

}

add_shortcode( 'form', 'form_shortcode' );

I know this isn't correct, but I'm having trouble figuring out exactly how this should even work logistically. Am I even close?

0

$atts['form_id'] contains the form_id that was passed with the Shortcode. You are searching for this form_id among the data that is held in the forms field.

$forms is an array, and each item in the array is another array with your two keys: form_id and form_markup.

So, for each item in $forms, you want to check if that form_id matches the form_id requested in the Shortcode. if there is a match, return the form_markup from that item.

If no matches were found, return an error message.

$forms = get_field( 'forms', 'option' );
foreach ( $forms as $form ) {
    if( $atts['form_id'] == $form['form_id'] ){
        return $form['form_markup'];
    }
}

return 'form id ' . $atts['form_id'] . ' not found';

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.