0

I have successfully populated a Gravity Forms drop down list with post tiles from main site in my network. See code below.

What code do I need to add in order to list post titles from sub-sites also?

Any insight is appreciated.

add_filter( 'gform_pre_render_20', 'select_questionnaire' );
add_filter( 'gform_pre_validation_20', 'select_questionnaire' );
add_filter( 'gform_pre_submission_filter_20', 'select_questionnaire' );
add_filter( 'gform_admin_pre_render_20', 'select_questionnaire' );
function select_questionnaire( $form ) {

    foreach ( $form['fields'] as &$field ) {

        if ( $field->type != 'select' || $field->id . '1' === false ) {
            continue;
        }

        $posts = get_posts( 'numberposts=-1&post_status=publish&post_type=questionnaire' );

        $choices = array();
        $choices[] = array("text" => "Select Questionnaire", "value" => "");

        foreach ( $posts as $post ) {
            $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
        }

        // update 'Select a Post' to whatever you'd like the instructive option to be

        $field->choices = $choices;

    }

    return $form;
}
0

You should be able to replace this section:

$posts = get_posts( 'numberposts=-1&post_status=publish&post_type=questionnaire' );

$choices = array();
$choices[] = array("text" => "Select Questionnaire", "value" => "");

foreach ( $posts as $post ) {
    $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
}

// update 'Select a Post' to whatever you'd like the instructive option to be

$field->choices = $choices;

with something like this:

$choices = array();
$sites = get_sites();
$choices[] = array("text" => "Select Questionnaire", "value" => "");
foreach ( $sites as $site ) {
    switch_to_blog( $site->blog_id );
    $posts = get_posts( 'numberposts=-1&post_status=publish&post_type=questionnaire' );
    foreach ( $posts as $post ) {
        $choices[] = array( 'text' => $post->post_title, 'value' => $post->post_title );
    }

    // update 'Select a Post' to whatever you'd like the instructive option to be

    restore_current_blog();
}
$field->choices = $choices;

By default, get_sites() returns up to 100 sites. You can filter this with various arguments.

Also, note that if you have a lot of sites in your Multisite network, or a lot of posts in your various sites, you should consider caching your results in a WordPress option or maybe site_option. switch_to_blog() can be expensive to run.

References

| improve this answer | |

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.