Object / Class not available in WordPress Theme files

I began digging into WordPress Theme development on a more OOP based approach, when I noticed something odd about the availability of the object you get when you write your custom theme functions as a class in functions.php.

To be fair, it's only odd because I've mainly been developing in other frameworks, which handle it after different conventions.

Object / Class Instance was not available in content.php

When I tested if the object was defined with var_dump(), I got a bare NULL in content.php, in index.php it would show up just fine.

$supertheme = new Supertheme();

The error message I got, when I tried to execute a function, that was part of the class in my theme:

Fatal error: Call to a member function post_thumbnail() on a non-object in /home/geronimo/public_html/theme_oop_wordpress_theme/wp-content/themes/oop_wordpress_theme/content.php on line 6

Making sure the Object is available in all WordPress Theme Files

To make sure the object of your object oriented theme is available in all files, or better, if you run in to issues, just put the following line on top of your theme file:

<?php global $your_object; ?>

$your_object refers to what ever name you've given your object when you created it in your functions.php:

if ( ! class_exists( 'your_class' ) ){
  class your_class {
    // your class code
  }
}
$your_object = new your_class();
?>

WordPress $post object

You can do the same to make the $post object available in included or required files, by using the same pattern. If you want to dig into what exactly the objects contain, just print their data with something like this, maybe in your index.php:

<?php
global $post;
echo '<pre>';
var_dump($post);
echo '</pre>';
?>
Tagged with: #WordPress

Thank you for reading! If you have any comments, additions or questions, please tweet or toot them at me!