0

I'm trying to get a different sidebar to load within child pages of a particular parent without the use of a plugin or setting up another template file.

This is what I have so far:

register_sidebars(1, array(
'name' => 'Other Sidebar',
'id' => "other-sidebar",
'before_widget' => '<li class="widget">',
'after_widget' => '</li>',
'before_title' => '<span class="widgettitle">',
'after_title' => '</span>'
));

if ( $post->post_parent == '1164' ) {
dynamic_sidebar( 'other-sidebar' );
}

But I'm wondering if I need use a filter of some sort to replace the default sidebar that is being loaded instead? Not too sure if that's correct or not.

ultraloveninja
  • 1,969
  • 5
  • 27
  • 56

1 Answers1

1

Since you can edit the theme (or child theme) you could add a Page Template that would override the current page template with the custom sidebar you want.

<?php 
/*
Template Name: Custom Sidebar Page // All versions
Template Post Type: page // 4.7+ only
*/

// Page code here with the sidebar you want...
?>

<aside id="secondary" class="widget-area" role="complementary">
    <?php dynamic_sidebar( 'other-sidebar' ); ?>
</aside><!-- #secondary -->

Then, in the edit for your page and it's child pages, set this template as the one you want.

Austin Winstanley
  • 1,339
  • 9
  • 19
  • Hmm, well, I was trying to set it to not use another template page either since that would possibly make a mess of things within the parent theme. But if anything, I might have to do that. – ultraloveninja Apr 18 '17 at 16:52
  • Copy the content of the parent theme's page template and then just replace the part you want. You could also deregister the default sidebar and register yours with the same name, but that would remove the default sidebar everywhere. – Austin Winstanley Apr 18 '17 at 17:04
  • Right, I only want to replace the current sidebar with a new one and only on certain pages. – ultraloveninja Apr 18 '17 at 21:08
  • Well, if you really don't want to do page templates, you can use your original code, check the parent id, and then `unregister_sidebar( 'default-sidebar' )` before registering your current one with the same name ('default-sidebar'). That way the template will use yours instead of the other. But this isn't a good idea. For one thing, it's hardcoded so if the page id changes, it won't work anymore. For another, it's not applicable in the admin section. So you can't change it anywhere else. It's just not very good architecture and could cause issues in the future. Your best bet is page templates. – Austin Winstanley Apr 18 '17 at 21:37