I have two loops on my page - each with their own category. It works, but I don't know if this is the best practice as I'm pretty new to this stuff.
<?php $my_query = new WP_Query( 'category_name=news&posts_per_page=3' );
while ( $my_query->have_posts() ) : $my_query->the_post();
$do_not_duplicate[] = $post->ID; ?>
<!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php $second_query = new WP_Query( 'category_name=reviews&posts_per_page=4' );
while ( $second_query->have_posts() ) : $second_query->the_post();
$do_not_duplicate[] = $post->ID; ?>
<!-- Do stuff... -->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
2 Answers 2
The only thing that changes between the first and second half is the query parameters.
<?php
foreach (array('news' => 3, 'reviews' => 4) as $category => $posts_per_page) {
$wp_query = new WP_Query(
"category_name=$category&posts_per_page=$posts_per_page"
);
while ( $wp_query->have_posts() ) {
# etc.
}
}
?>
Since you don't have any literals in this PHP file you don't need to open and close the PHP tags all over the place.
Here is how it would look if you did what I am saying.
<?php
$my_query = new WP_Query( 'category_name=news&posts_per_page=3' );
while ( $my_query->have_posts() ) :
$my_query->the_post();
$do_not_duplicate[] = $post->ID;
get_template_part( 'content', get_post_format() );
endwhile;
$second_query = new WP_Query( 'category_name=reviews&posts_per_page=4' );
while ( $second_query->have_posts() ) :
$second_query->the_post();
$do_not_duplicate[] = $post->ID;
get_template_part( 'content', get_post_format() );
endwhile;
?>
This makes it much clearer what your code is doing.
I would rewrite it like this and double check that the code is actually doing what you want it to do. My guess is that you have copy pasted this code from somewhere and are trying to alter it to fit your purposes.
-
\$\begingroup\$ I think the excessive opens and closes are part of the standard for WordPress templates. They do this in part to make it easy to add HTML. \$\endgroup\$Brythan– Brythan2015年01月09日 19:08:43 +00:00Commented Jan 9, 2015 at 19:08
<!-- Do stuff... -->
was just comments that were part of the paste. this is functioning code. I'm not sure why this is off-topic, I'm new to the site and was (perhaps mistakenly) under the impression this question fit within the parameters. \$\endgroup\$<?php ?>
tags. everything inside of them is PHP code. \$\endgroup\$