I’ve got a registered sidebar called “my-header” that affects the absolute positioning of elements below it in the markup.
So I need to execute a query in header.php to determine if the sidebar is present for the current post, and write out a class identifier to my theme’s body tag. I’ll use this css class to adjust absolute positioning of elements accordingly.
Is there a method that can be called, separately from the method that’s used to display the sidebar, to determine if the post has widget content for the “my-sidebar” widget? For example, one that just returns true/false?
After looking through widgets.php, I tried using is_active_sidebar(‘my-header’) but it returns true for all pages. I need a function that accepts the post as an argument. Otherwise, if none exists, I suppose I’ll create my own function.
1 Answer
<?php
$bodyclass = "";
// are we on a 'single' page? e.g. a post or page or some other custom post type?
if(is_single()){
// is this a post of type 'page'? or is it a blogpost?
global $post;
if($post->post_type == 'page'){
// good now to check if we have a sidebar with active content
if( is_active_sidebar('my-header')){
$bodyclass="wehavesidebarcontentyay";
}
}
}
?>
<body <?php body_class($bodyclass); ?>>
Though I’m sure if you have body_class on your body tag then you already have the needed css classes and selectors to do this without the PHP code.