Why does a variable work on the front page but return NULL on all other pages?

Hey all. For my theme, I have multiple sidebars. Each sidebar file has a variable of $sidebar_id assigned to it. So, for sidebar-1.php, $sidebar_id = 1, for sidebar-2.php, $sidebar_id = 2, and so on. Each sidebar has an action hook inside of it.

Then I write a function to hook on to the sidebar action hook. Within the function, I reference $sidebar_id to display different content in different sidebars. WordPress recognizes the value of $sidebar_id on the front page.

Read More

But on archive pages, single pages and single posts, $sidebar_id always returns NULL. Even if I declare it as a global in my function. I don’t get why the function can recognize the variable on the front page but it can’t on all other pages. Any insights would be greatly appreciated.

For example, here is my function:

function archive_only() {
global $sidebar_id;
if($sidebar_id == "archives") {
echo "only show on archive sidebar"; 
    }
} add_action('cpress_sidebar_after', 'archive_only'); 

It works on the front page but doesn’t on any other pages. $sidebar_id is defined in the sidebar template files.

Related posts

Leave a Reply

1 comment

  1. Hi @orbit82:

    Searching through the code in WordPress v3.0.4 I was unable to find any references to a global $sidebar_id so I am assuming that either your theme is setting it on the front page or a plugin you are using is setting it. Can you verify?

    What’s more, I would definitely echo @prettyboymp’s comment that you should look to use the conditional tags like is_single() and is_archive(); is there a reason they won’t work for you? Here’s a reference on the WordPress Codex for what conditional tags are available in WordPress: