WordPress and page templates

by on July 28, 2014

In the WordPress universe there exist page templates – and different templates load under different circumstances. This was how I generated Table of Content pages and album pages inside of the WordPress site. Let’s start with a template for an empty page:

<?php get_header(); ?>


<div id="content">
	<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
	<div class="post">
	<h1><?php the_title(); ?></h1>
	
	<?php the_content('Read the rest of this entry &raquo;'); ?>
	<?php comments_popup_link('0 comments', '1 Comment', '% Comments'); ?>
	<?php edit_post_link('edit page', '<p>[', ']</p>'); ?>
	</div>
	<?php endwhile; else: ?>
	<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
	<?php endif; ?>
	
  
</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

In order to generate a table of contents, we’re going to make some changes to this code. Let’s start by adding a call to insert some content right after call to the WP function edit_post_link

	<?php edit_post_link('edit page', '<p>[', ']</p>'); ?>
	</div>
  <!-- new code starts here -->
  <div class="TOC">
  <?php 
    $custom_fields = get_post_custom();
    print get_toc($custom_fields['country_code'][0]); 
  ?>
  </div>
  <!-- and ends here -->

We’ve added a DIV whose appearance we can control via CSS, and a call to a function to load the actual content. So far, so good. We use a custom field to store the country code, then access the custom field to call our function that generates the page content.

Album pages work in a similar way, except that we now have an additional custom field.

<?php
  $q = "SELECT country_code, virtual_page, htm "
     . "FROM stamp_web_content "
     . "WHERE country_code = '{$GLOBALS['country_code']}' "
     . "  AND virtual_page = '{$GLOBALS['page_id']}' ";
  $r = $wpdb->get_row($q, ARRAY_A);  
  echo $r['htm'];
  ?>

In case you’re wondering about “$wpdb”, it’s a global reference to the database used by WordPress. Since the stamp html content resides in the same database, it can be accessed via this variable. The table stamp_web_content contains only a few fields, one of which is the pre-built html for each virtual album page. I used this as a poor-man’s cache system, since building each page under WP was painfully slow.

An excellent article on using this functionality can be found here: WordPress Essentials: Interacting With The WordPress Database.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>