Hierarchy of Templates

The title of the paragraph should have been: “Breaking Wordpress Hierarchy of Templates”. It was even simpler that I have expected. I am sure that most of the reader will not find here anything new, but this was the first Wordpress theme and I felt great when I have discovered the little hack. Here is what I did to break hierarchy of Wordpress templates. Every theme has (should have) functions.inc file. I have put int it the following:

<?php
. . .
    function content_posts () {
        include(TEMPLATEPATH . ‘/content_posts.php’);
        exit;
    }
    if (isset($_POST[‘backgroundPosts’])) {
        add_action(‘template_redirect’, ‘content_posts’);
    }
. . .
?>

To make content_posts.php Wordpress stuff has to be included into it. This is how the content_posts.php could look like:

<?php
if(!function_exists(‘get_option’))
    require_once(‘../../../wp-config.php’);
    global $comments, $post, $wpdb;
?>
<div id="content">
    <?php while (have_posts()) : the_post(); ?>
        <div class="post">
            <div class="title"><?php the_title(); ?></div>
            <div class="body"><?php the_content(‘More…’); ?></div>
        </div>
    <?php endwhile; ?>
</div>

As you can see, the content_posts.php contains all the stuff that index.php contains in typical Wordpress theme, except of header and footer inclusion. The “hack” is as follows: when the client (browser) calls Wordpress’, then home/index.php is called. My theme index.php has just header and footer inclusion; no content; no Wordpress loop. After it loads Ext posts the server of the referef plus backgroundPosts parameter, then content_posts.php is called and the result is printed into a ‘wp-posts’ area. (To be more exact index.php contains object with id=”wp-posts”.) Please take a look on loadPost function from theme.js.

<script>
. . .
    loadPosts: function(url) {
        Ext.get(‘wp-posts’).load({
            url: url,
            params: {backgroundPosts: true},
        });
    },
. . .
</script>