Part 3 Learning Objectives
- Work with custom fields and post metadata
- Master conditional tags
- Learn proper data escaping
- Create custom template functions
Data Escaping Best Practices
// Escape HTML
<h1><?php echo esc_html( get_the_title() ); ?></h1>
// Escape URLs
<a href="<?php echo esc_url( get_permalink() ); ?>">Link</a>
// Escape attributes
<input value="<?php echo esc_attr( $value ); ?>">
// Escape JavaScript
<script>
var title = '<?php echo esc_js( get_the_title() ); ?>';
</script>
Creating Custom Template Functions
// Custom post metadata function
function my_theme_post_meta() {
$output = '<div class="post-meta">';
$output .= '<span>By ' . get_the_author() . '</span>';
$output .= '<span>' . get_the_date() . '</span>';
$categories = get_the_category();
if ( ! empty($categories) ) {
foreach($categories as $cat) {
$output .= '<a href="' . get_category_link($cat->term_id) . '">';
$output .= $cat->name . '</a> ';
}
}
$output .= '</div>';
echo $output;
}
// Reading time calculator
function my_theme_reading_time() {
$content = get_the_content();
$word_count = str_word_count(strip_tags($content));
$reading_time = ceil($word_count / 200);
echo $reading_time . ' min read';
}
Complete Template Example
<article <?php post_class(); ?>>
<?php if ( has_post_thumbnail() ) : ?>
<div class="featured-image">
<?php the_post_thumbnail('large'); ?>
</div>
<?php endif; ?>
<header>
<?php the_title('<h1>', '</h1>'); ?>
<div class="meta">
<?php the_author_posts_link(); ?>
<?php echo get_the_date(); ?>
<?php the_category(', '); ?>
</div>
</header>
<div class="entry-content">
<?php the_content(); ?>
</div>
<footer>
<?php the_tags('Tags: ', ', ', ''); ?>
</footer>
</article>
Best Practices Summary
- Always escape output with appropriate functions
- Use conditional tags to check before displaying
- Cache expensive operations in variables
- Use get_ functions when manipulating data
- Provide fallbacks for missing data
- Internationalize all text strings