4 ms·
The reason that many people think the WP loop is badly constructed is because it entirely works by side effects. A (very simple) WP loop looks like this:
by vec 13y ago
The reason that many people think the WP loop is badly constructed is because it entirely works by side effects. A (very simple) WP loop looks like this:
<?php while (have_posts()) : the_post() ?>
<h2><?php the_title() ?></h2>
<?php the_content() ?>
<?php endwhile ?>
There are four unique functions there. All of them depend on non-obvious global state and three of them are used specifically to produce side effects. the_post() invisibly overwrites a global and changes an iterator. It not only mutates global state, but it does something different if you accidentally call it twice. And WP's the_whatever() functions echo something and return nothing?! Want to do some filtering on the title before you print it? Better use get_the_whatever() instead. WTF?! Heres how it should work:
<?php foreach ($post in $wpdb->get_posts() : ?>
<h2><?= $post->title ?></h2>
<?= $post->content ?>
<?php endforeach ?>
- jwarren 13y agoYou're completely right on that, and I couldn't agree more; the mystery of the global states is frustrating to a new WP developer. Additionally, Wordpress has tons and tons of bad functions. If so many themes weren't dependent on them, I'd advocate for entirely stripping out a good chunk of them. Someone needs to write Wordpress: The Good Parts, or at least a really canonical good practise guide. I guess it could be a good weekend project. For the functions you mention, you're actually not too far off what they really do. the_title() [1] is just slightly formatting get_the_title [2], which is mostly just returning $post->post_title. Unfortunately, skipping the built-in functions means also skipping the slightly obtuse but powerful filter system. However, if you're not interested in the built in WP stuff, then there's no harm in outputting the titles directly. Btw, yes, I realise this is mostly academic in the context we're talking about. [1]: http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/post-template.php#L71 http://core.trac.wordpress.org/browser/tags/3.5.1/wp-include... [2]: http://core.trac.wordpress.org/browser/tags/3.5.1/wp-includes/post-template.php#L102 http://core.trac.wordpress.org/browser/tags/3.5.1/wp-include...