0

sorry, if this is a stupid question, but I am relatively new to php and wordpress development.

I am writing a plugin with a custom post type (course) where a parent page is the course overview and the child pages are the lessons.

Now my aim is to replace the content of the sidebar. If the page is a parent cpt then content of sidebar A should be displayed. If the page is a child cpt then the content of sidebar B should be displayed.

So what I am trying to do is to stop loading the widgets of the normal theme sidebar and replace them with the widgets from sidebar a or b.

I was able to:

  • create a dropdown in the backend, where the sidebar which should be replaced can be selected.
  • register two new sidebars (in design > widgets) (with register_sidebar).
  • check if the page is a parent cpt or a child ctp
    if ( is_singular('courses') && $post->post_parent && is_active_sidebar( 'courses-lessons-sidebar' ) ) or
    if ( is_singular('courses') && ! $post->post_parent && is_active_sidebar( 'courses-overview-sidebar' ) )

But what I do not understand is, how to tell WordPress to stop loading the widgets from the normal sidebar, but from one of the new sidebars!?

I tried a lot of things and thought I found a solution with injecting the widgets with dynamic_sidebar_before and then stop rendering the normal sidebar with "exit", but this leads to unwanted problems (e.g. mobile menu is no longer visible, etc.)

And by the way: I would need the solution to be theme independent :)

I really hope that there is someone out there who can help me! Thank you very much in advance! Best regards! Tioata

1 Answer 1

0

After a lot of trying and testing, I think I've found a solution:

add_filter( 'sidebars_widgets', 'exchange_sidebars', 10);

function exchange_sidebars( $sidebars_widgets ){
    global $post;
    // Define the sidebar which should be exchanged
    $selected_sidebar = 'sidebar-1'

    // IF we are on a custom post type
    // AND it is a Child Page (= page has post_parent)
    // THEN change selected sidebare with courses-lessons sidebar
    if ( is_singular('courses') && $post->post_parent && $sidebars_widgets['courses-lessons-sidebar'] ) {
        $sidebars_widgets[$selected_sidebar] = $sidebars_widgets['courses-lessons-sidebar'];

    // IF we are on a custom post type
    // AND it is a Parent Page (= page has no post_parent)
    // THEN change selected sidebare with courses-overview sidebar
    }elseif( is_singular('courses') && !$post->post_parent && $sidebars_widgets['courses-overview-sidebar'] ) {
        $sidebars_widgets[$selected_sidebar] = $sidebars_widgets['courses-overview-sidebar'];
    }
    return $sidebars_widgets;
}

Just in case someone else is interested in the solution ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.