Created
March 12, 2014 12:33
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// The basic `for` loop | |
for ( $i = 0; $i < 10; $i++ ) { | |
// Do iterative work | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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