viankakrisna
1/14/2016 - 8:46 AM

Calibrefx Dynamic Sidebar (Create and display sidebar based on post type)

Calibrefx Dynamic Sidebar (Create and display sidebar based on post type)

<?php

add_action( 'widgets_init', 'childfx_widgets_init' );
function childfx_widgets_init() {
    //TODO: Create setting in admin area for this variable
    $post_type = array(
        'news',
        'post'
    );

    foreach ($post_type as $value) {
        $valuename = ucfirst($value);
        register_sidebar( array(
            'name' => __( "$valuename Sidebar", 'calibrefx' ),
            'id' => "$value-sidebar",
            'description' => __( "Widgets in this area will be shown on {$valuename} posts and pages.", 'calibrefx' ),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
        'after_widget'  => '</div>',
        'before_title'  => '<h2 class="widgettitle">',
        'after_title'   => '</h2>',
        ) );
    }
}

add_filter('calibrefx_sidebar_default', 'childfx_sidebar');
function childfx_sidebar( $sidebar ) {
    $post_type = get_post_type();
    if ( is_active_sidebar( "$post_type-sidebar" ) ) {
        $sidebar = get_dynamic_sidebar( "$post_type-sidebar" );
    }
    return $sidebar;
}

function get_dynamic_sidebar($index = 1){
    $sidebar_contents = "";

    ob_start();
    dynamic_sidebar($index);
    $sidebar_contents = ob_get_clean();

    return $sidebar_contents;
}