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 😉