0

I'm trying to conditionally add a class of has-sidebar to a wrapper div, and I'm struggling to find a conditional statement to see if the sidebar is active on the current page.

For example:

<!-- Open site main wrapper -->
    <div id="site-content" <?php if (is_active_sidebar('sidebar-1')) echo 'class="has-sidebar"' ?>>

The issue is "is_active_sidebar" is always returning true - is there a function or conditional I can check to see if a sidebar is displayed or not?

1 Answer 1

1

Because of the way templates are rendered in WordPress it won't be possible to know if a page has a sidebar until after that sidebar has been rendered. This is because code in templates can't 'know' what code exists later in rendering sequence.

What I would recommend is determining what the conditions are which your sidebar is displayed under and using those conditions in your has-sidebar check. For example, if your wrapper opens in header.php but your sidebar is only displayed on posts by rendering it in single.php only, you could check is_single() in header.php to determine whether the sidebar is going to be rendered. You could combine this with is_active_sidebar() if you need to know of the sidebar will have any widgets in it.

1
  • Yep that worked, I was going about it the wrong way. Thanks!
    – Sackadelic
    Jan 21, 2023 at 14:04

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.