在多站点网络中使用帖子标题填充下拉列表

时间:2018-01-11 作者:Mario

我已经成功地在重力表单下拉列表中填充了来自网络主站点的贴片。请参见下面的代码。

为了列出子网站的帖子标题,我需要添加什么代码?

任何见解都将不胜感激。

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;
}

1 个回复
最合适的回答,由SO网友:Pat J 整理而成

您应该能够替换此部分:

$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;
用这样的方式:

$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;
默认情况下,get_sites() 返回最多100个站点。您可以使用各种参数对此进行筛选。

另外,请注意,如果您的多站点网络中有很多站点,或者您的各个站点中有很多帖子,那么您应该考虑将结果缓存在WordPress选项或site\\u选项中。switch_to_blog() 运行成本可能很高。

参考文献get_sites()
  • switch_to_blog()
  • restore_current_blog()
  • 结束