代码之家  ›  专栏  ›  技术社区  ›  Aness

如何在不打印的情况下获取Wordpress小部件(侧栏)?

  •  0
  • Aness  · 技术社区  · 5 年前

    我正在使用Wordpress和PHP。我使用以下代码声明了一个自定义边栏:

       function customtheme_widgets_init() {
    register_sidebar( array(
      'name'          => esc_html__( 'My custom sidebar', 'customtheme' ),
      'id'            => 'my-custom-sidebar',
      'description'   => esc_html__( '.', 'customtheme' ),
      'before_widget' => '',
      'after_widget'  => '',
      'before_title'  => '',
      'after_title'   => '',
    ) );
    }
    add_action( 'widgets_init', 'customtheme_widgets_init' );
    

    好的,所以在我的代码中,我想获取侧边栏并将其存储在一个PHP变量中 $小部件 . 使用此代码:

    if ( is_active_sidebar( 'my-custom-sidebar' ) ) :
        $the_widget = dynamic_sidebar('my-custom-sidebar');
    endif;
    

    1 回复  |  直到 5 年前
        1
  •  1
  •   Bryan Elliott    5 年前

    不不幸的是没有像这样的WordPress函数 get_dynamic_sidebar()

    if ( is_active_sidebar( 'my-custom-sidebar' ) ) :
        ob_start();
        dynamic_sidebar('my-custom-sidebar');
        $the_widget = ob_get_contents();  //or ob_get_clean();
        ob_end_clean();
    endif;
    
    推荐文章