Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tommcfarlin/e54038ff7e6571a13279 to your computer and use it in GitHub Desktop.
Save tommcfarlin/e54038ff7e6571a13279 to your computer and use it in GitHub Desktop.
[WordPress] An second, more general example of how using a variable even if it's only to be used once can improve the readability of code.
<?php
// The basic `for` loop
for ( $i = 0; $i < 10; $i++ ) {
// Do iterative work
}
<?php
/* The basic `for` loop with the length of the collection
* being stored once so it isn't checked every time
* the loop runs.
*/
for ( $i = 0, $l = 10; $i < $l; $i++ ) {
// Do iterative work
}
/* A second example as to how storing the size
* of the results can result in a more performant
* loop.
*
* Assume the arguments for retrieving posts have
* already been defined.
*/
$args = array(
'post_type' => 'acme_post_type',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'acme_labels'
'field' => 'term_id',
'terms' => 100
),
array(
'taxonomy' => 'acme_labels',
'field' => 'term_id',
'terms' => 200
)
)
);
$posts = get_posts( $args );
$post_count = count( $posts );
for ( $i = 0; $i < $post_count; $i++ ) {
// Do iterative work
}
<?php
/* A second example as to how storing the size
* of the results can result in a more performant
* loop.
*
* Assume the arguments for retrieving posts have
* already been defined.
*/
$args = array(
'post_type' => 'acme_post_type',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'acme_labels'
'field' => 'term_id',
'terms' => 100
),
array(
'taxonomy' => 'acme_labels',
'field' => 'term_id',
'terms' => 200
)
)
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
// Do iterative work
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment