plugin development – Replace Content of Sidebar on Custom Post Type


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 year 2021-08-08T14:19:56-05:00 0 Answers 0 views 0

Leave an answer