WordPress: Convenience Isn't Always Convenient

WordPress is a fantastic platform to develop in, especially when you start coding your own themes from scratch. No poorly coded templates, and no bloated plugins that are constantly behind the curve.

The WordPress Loop is something that we all use when qeurying post data:

<?php
while (have_posts()) : the_post();
the_title(); // the title of the post
the_content(); // the content within the editor for the post
endwhile;
?>

That looks familiar, doesn’t it? While this is a perfectly acceptable way to utilize the WordPress Loop, I’d like to direct you to a statement made within the WordPress codex:

The have_posts() and the_post() are convenience wrappers around the global $wp_query object, which is where all of the action is.

Many new WordPress theme developers get stuck using the convenience methods like the_title(), the_content(), and the_permalink(). Again, while this is perfectly acceptable, I find that using the global $post variable, and accessing the attributes of the post directly is far more flexible, and far more efficient when rendering your post data:

<?php
while (have_posts()) : the_post();
echo $post->post_title; // the title of the post
echo $post->post_content; // the content within the editor for the post
endwhile;
?>

That last snippet of code produces the exact same result as the first block, but instead of relying on the convenience methods, you can actually echo the raw data from the $post object directly.

Want to know what else you can utilize within the $post object? Give this bit of code a whirl:

<?php
while (have_posts()) : the_post();
echo "<pre>";
var_dump($post);
endwhile;
?>

Now isn’t that special? 🙂 Have fun!

SIGN UP FOR OUR NEWSLETTER

DON'T WORRY WE HATE SPAM TOO!

RELATED ARTICLES

READY TO BE EXCEPTIONAL? CALL (250) 661-9496 NOW!

Rated Top SEO Agency - Muller Consulting
© AM2 Holdings Corp - 
Muller Consulting 2022