• Resolved warwickmusic1

    (@warwickmusic1)


    Hi.

    I’m trying to build a version of the wordpress search results page.

    I’ve tried to find a basic example of the loop I need to put on the page to display the results, but after Googling, I can’t find a straight forward answer.

    What I’ve currently written clearly has errors in the code because it will only render 1 result on each paginated page. I want it to return 25 results per page from a specific category (165).

    I’ve discovered that when I remove infinite scroll the paginated results are in fact only displaying 12 posts when there are actually 36 in category 165.

    To compound the problem I am trying to use Metafizy’s Isotope filtering and Jquery infinite scroll to display my results, which is making my code hard to follow.

    I think the problem is in the fact I’m using query_posts to display my results, but this new WP_Query I’ve written further down the page (see code).

    All in all, I’m quite confused at this point. I’d really appreciate it if someone could provide me with the simple loop I need to add to search.php in my theme so it will render all 36 results from category 165 with the results being paginated with each paginated page displaying 25 posts.

    Here is my current code.

    <?php
    /**
     * The template for displaying Search Results pages.
     *
     * @package WordPress
     * @subpackage pBone
     */
    if ( ! defined( 'ABSPATH' ) ) {
    	exit; // Exit if accessed directly.
    }
    get_header(); 
    ?>
    
    <div id="wrapper" class="container d-sm-flex">
    
    	<div class="">
    		
    		<?php query_posts( array('paged' => get_query_var('paged'), 'post_type' => array( 'post'), 's' => $s ) ); if ( have_posts() ): ?>
    		<h2>Search results for: <?php echo get_search_query(); ?></h2>
    		<div class="filters" id="collapseExample">
    			<div class="ui-group">
    				<p class="text-monospace m-0">Choose an instrument</p>
    				<div class="button-group js-radio-button-group d-flex flex-wrap" data-filter-group="instrument">
    					<button class="btn btn-primary button is-checked mr-1 mb-1" type="button" data-filter="">any</button>
    					<?php 
    					$terms = get_terms( 'category', array('parent' => 165)); // get all categories, but you can use any taxonomy
    					$count = count($terms); //How many are they?
    					if ( $count > 0 ){  //If there are more than 0 terms
    					foreach ( $terms as $term ) {  //for each term:
    					echo "<button class='button btn btn-primary mr-1 mb-1' type='button' data-filter='.".$term->slug."'>" . $term->name . "</button>\n";
    					//create a list item with the current term slug for sorting, and name for label
    					}
    					} 
    					?>
    				</div>
    			</div>
    
    			<div class="ui-group">
    				<p class="text-monospace m-0">Pick your resource type</p>
    				<div class="button-group js-radio-button-group d-flex flex-wrap" data-filter-group="type">
    					<button class="button is-checked btn btn-primary mr-1 mb-1" type="button" data-filter="">any</button>
    					<?php
    					$field_key = "field_5ed77f279f5e2";
    					$field = get_field_object($field_key);
    
    					if( $field )
    					{
    
    							foreach( $field['choices'] as $k => $v )
    							{
    								echo '<button class="button btn btn-primary mr-1 mb-1" type="button" data-filter=".' . $k . '">' . $v . '</button>';
    							}
    
    					}
    					?>
    				</div>
    			</div>
    		</div>
    		<?php 
    			 $terms_ID_array = array();
    			 foreach ($terms as $term)
    			 {
    				 $terms_ID_array[] = $term->term_id; // Add each term's ID to an array
    			 }
    			$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
    			 $terms_ID_string = implode(',', $terms_ID_array); // Create a string with all the IDs, separated by commas
    			 //$the_query = new WP_Query( 'posts_per_page=3&cat='.$terms_ID_string ); // Display 50 posts that belong to the categories in the string
    			$the_query = new WP_Query ( array(
    				//'cat' => $terms_ID_string,
    				'posts_per_page' => 25,
    				'paged' => $paged
    			));
    		?>
    		<?php if ( $the_query->have_posts() ) : ?>
    		<div id="Grid" class="article-feed grid d-md-flex pt-4">
    
    			<?php while ( have_posts() ) : the_post(); 
    				$termsArray = get_the_terms( $post->ID, "category" );  //Get the terms for this particular item
    				$termsString = ""; //initialize the string that will contain the terms
    				foreach ( $termsArray as $term ) { // for each term 
    					$termsString .= $term->slug.' '; //create a string that has all the slugs 
    				}
    			?>
    			<?php
    			$colors = get_field('content-type');
    			if( $colors ): 
    			
    			?>
    			
    			<?php foreach( $colors as $color ): ?>
    			<?php $color = strtolower($color); ?>
    			<?php $color = str_replace(' ', '-', $color); ?>
    			<div data-src="<?php echo $color; ?>" class="article infinite-item item <?php echo $termsString;?> <?php echo $color; ?> col-md-6 col-lg-4 mb-4 hidden-opacity">
    				<?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
    				
    			<div class="c-opus__box  u-box-shadow card ">
    
    				<?php if ( has_post_thumbnail() ) : ?>
    					<div class="thumbnail">
    						<span>
    							<div class="isotope-im-wrapper col d-flex align-items-center justify-content-center p-0 pt-4 pt-md-0">
    							<?php
    								$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
    							?>
    							<!-- Standard version -->
    							<img class="img-fluid card-img-top" src="<?php the_post_thumbnail_url(); ?>"/>
    							</div>
    						</span>
    					</div>
    				<?php endif; ?>
    				<div class="card-body ">
    					<h3 class="u-h4 c-opus__title  u-margin-bottom-small card-title"><?php the_title(); ?></h3>
    					<div class="o-layout">
    						<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>
    					</div>
    					<?php if(get_field('hubspot_cta_embed_code')): ?>
    						<?php the_field('hubspot_cta_embed_code'); ?>
    					<?php endif; ?>
    					<?php if(get_field('keyword_tags')): ?>
    					<div class="keyword-tags">
    						<hr class="my-4">
    						<p class="lead"><strong>Tags</strong></p>
    						<?php the_field('keyword_tags'); ?>
    					</div>
    					<?php endif; ?>
    				</div>
    			</div>
    			<?php endforeach; ?>
    			</div>
    			</div><!-- end isotope-list -->
    			<?php else : ?>
    			</div><!-- end isotope-list -->
    			<?php endif; ?>	
    			<?php endwhile; ?>
    			<!-- status elements -->
    			<div class="scroller-status" style="display: block;">
    				  <div class="loader-ellips infinite-scroll-request" style="display: none;">
    					<span class="loader-ellips__dot"></span>
    					<span class="loader-ellips__dot"></span>
    					<span class="loader-ellips__dot"></span>
    					<span class="loader-ellips__dot"></span>
    				  </div>
    				  <p class="scroller-status__message infinite-scroll-last" style="display: block;">End of content</p>
    				<div class="scroller-status__message infinite-scroll-error" style="display: none;"><p>No results found</p></div>
    
    			</div>
    			<p class="pagination">
    				<?php previous_posts_link( 'Older posts' ); ?>
    				<?php next_posts_link( 'Newer posts' ); ?>
    			</p>
    		<?php wp_reset_postdata(); ?>
    		<?php else: ?>
    		<h2>No search results for: <?php echo get_search_query(); ?></h2>
    		<?php endif; ?>
    			</div><!-- #wrapper -->
    		</div>
    	<?php else : ?>
    			No results found please use a different search term.
    		</div>
    	</div>
    	<?php endif; ?>
    
    <?php get_footer(); ?>
    

    The page I need help with: [log in to see the link]

Viewing 11 replies - 1 through 11 (of 11 total)
  • Moderator bcworkz

    (@bcworkz)

    A lot of pagination doesn’t work very well when new queries are involved, which is what query_posts() does. For optimal pagination behavior (and more efficient querying), alter the default query through “pre_get_posts” action. From there you can get and set query vars to match anything you’d try to do with query_posts() or a new WP_Query, plus all normal pagination (and quasi-related infinite scroll) should continue to work as expected.

    Just be sure you only alter the right query, as all sorts of queries run through this action. Usually you’d at least check if WP_Query::is_main_query() is true.

    Thread Starter warwickmusic1

    (@warwickmusic1)

    Hi @bcworkz

    Thanks for taking the time to write a reply to me here. This has given me something to go on but I’m still struggling to understand how to implement this.

    I found this code that seems to be along the lines of what you speak of

    function change_wp_search_size($query) {
    	if ( $query->is_search ) // Make sure it is a search page
    		$query->query_vars['posts_per_page'] = 10; // Change 10 to the number of posts you would like to show
    
    	return $query; // Return our modified query variables
    }
    add_filter('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

    But, I don’t know how to use it.

    I’ve now switched over to using the default Twenty Twenty theme to remove any theme conflicts. I’ve then placed the above code into the Twenty Twenty functions.php file. I’ve copied over the custom search.php file into the Twenty Twenty theme and removed <?php query_posts( array('paged' => get_query_var('paged'), 'post_type' => array( 'post'), 's' => $s ) ); if ( have_posts() ): ?>

    I also removed the custom query

    			$the_query = new WP_Query ( array(
    				//'cat' => $terms_ID_string,
    				'posts_per_page' => 25,
    				'paged' => $paged
    			));
    

    and changed <?php if ( $the_query->have_posts() ) : ?> to just <?php if (have_posts() ) : ?>

    So, my understanding is that I now have the default WordPress query on the page and that the code added to functions.php should see that query as a search query because it is on the search.php file and so change the number of posts displayed to 10.

    Sadly, I’m still only getting back 1 search result per page.

    Thread Starter warwickmusic1

    (@warwickmusic1)

    Hi,

    So a further development with this.

    I do seem to now be able to control the number of search results on the page using the below code in functions.php, but only if the search query in the URL field is empty. i.e. domain.com/?s=

    function change_wp_search_size($query) {
    	if ( $query->is_search ) // Make sure it is a search page
    		$query->query_vars['posts_per_page'] = 36; // Change 36 to the number of posts you would like to show
    
    	return $query; // Return our modified query variables
    }
    add_filter('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

    on the results search.php page, I now set a new Wp_Query object called $the_query like so

    
    	$the_query = new WP_Query ( array(
    		'posts_per_page',
    	));
    

    I then call the have_posts function like this <?php if ( $the_query->have_posts() ) : ?>

    When the URL search query is empty like domain.com/?s= I get 36 posts back per page and I can change the number of posts displaying by altering the code in functions.php, this works great, but as soon as I add a search term like domain.com/?s=my+search+query it just returns 5 results per page now.

    The full code for the search.php results page now reads like this.

    
    <?php
    /**
     * The template for displaying Search Results pages.
     *
     * @package WordPress
     * @subpackage xxxx
     */
    if ( ! defined( 'ABSPATH' ) ) {
    	exit; // Exit if accessed directly.
    }
    get_header(); 
    ?>
    
    <div id="wrapper" class="container">
    
    			<h2>Search results for: <?php echo get_search_query(); ?></h2>
    			<div class="filters" id="collapseExample">
    				<div class="ui-group">
    					<p class="text-monospace m-0">Choose an instrument</p>
    						<div class="button-group js-radio-button-group d-flex flex-wrap" data-filter-group="instrument">
    							<button class="btn btn-primary button is-checked mr-1 mb-1" type="button" data-filter="">any</button>
    								<?php 
    								$terms = get_terms( 'category', array('parent' => 165)); // get all categories, but you can use any taxonomy
    								$count = count($terms); //How many are they?
    								if ( $count > 0 ){  //If there are more than 0 terms
    								foreach ( $terms as $term ) {  //for each term:
    								echo "<button class='button btn btn-primary mr-1 mb-1' type='button' data-filter='.".$term->slug."'>" . $term->name . "</button>\n";
    								//create a list item with the current term slug for sorting, and name for label
    								}
    								} 
    								?>
    						</div>
    					</div>
    
    					<div class="ui-group">
    						<p class="text-monospace m-0">Pick your resource type</p>
    							<div class="button-group js-radio-button-group d-flex flex-wrap" data-filter-group="type">
    								<button class="button is-checked btn btn-primary mr-1 mb-1" type="button" data-filter="">any</button>
    									<?php
    									$field_key = "field_5ed77f279f5e2";
    									$field = get_field_object($field_key);
    
    									if( $field )
    									{
    
    											foreach( $field['choices'] as $k => $v )
    											{
    												echo '<button class="button btn btn-primary mr-1 mb-1" type="button" data-filter=".' . $k . '">' . $v . '</button>';
    											}
    
    									}
    									?>
    							</div>
    						</div>
    					</div>
    					<?php 
    						 $terms_ID_array = array();
    						 foreach ($terms as $term)
    						 {
    							 $terms_ID_array[] = $term->term_id; // Add each term's ID to an array
    						 }
    						 $terms_ID_string = implode(',', $terms_ID_array); // Create a string with all the IDs, separated by commas
    						$the_query = new WP_Query ( array(
    							'posts_per_page',
    						));
    					?>
    					<?php if ( $the_query->have_posts() ) : ?>
    					<div id="" class="article-feed d-md-flex pt-4 flex-wrap">
    
    					<?php while ( have_posts() ) : the_post(); 
    						$termsArray = get_the_terms( $post->ID, "category" );  //Get the terms for this particular item
    						$termsString = ""; //initialize the string that will contain the terms
    						foreach ( $termsArray as $term ) { // for each term 
    							$termsString .= $term->slug.' '; //create a string that has all the slugs 
    						}
    					?>
    					<?php
    					$colors = get_field('content-type');
    					if( $colors ): 
    
    					?>
    			
    					<?php foreach( $colors as $color ): ?>
    						<?php $color = strtolower($color); ?>
    						<?php $color = str_replace(' ', '-', $color); ?>
    							
    						<?php // 'item' is used as an identifier (see Setp 5, line 6) ?>
    							<div data-src="<?php echo $color; ?>" class="article infinite-item item <?php echo $termsString;?> <?php echo $color; ?> col-md-6 col-lg-4 mb-4 hidden-opacity">
    								<div class="c-opus__box  u-box-shadow card ">
    
    								<?php if ( has_post_thumbnail() ) : ?>
    									<div class="thumbnail">
    										<span>
    											<div class="isotope-im-wrapper col d-flex align-items-center justify-content-center p-0 pt-4 pt-md-0">
    												<?php
    													$thumbnail = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
    												?>
    												<img class="img-fluid card-img-top" src="<?php the_post_thumbnail_url(); ?>"/>
    											</div>
    										</span>
    									</div>
    								<?php endif; ?>
    									<div class="card-body">
    
    										<h3 class="u-h4 c-opus__title  u-margin-bottom-small card-title"><?php the_title(); ?></h3>
    
    										<div class="o-layout">
    											<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>
    										</div>
    										<?php if(get_field('hubspot_cta_embed_code')): ?>
    											<?php the_field('hubspot_cta_embed_code'); ?>
    										<?php endif; ?>
    									</div>
    								</div>
    							</div>
    					<?php endforeach; ?>
    			
    
    			<?php else : ?>
    			
    			<?php endif; ?>	
    			<?php endwhile; ?>
    			</div>
    		<!-- status elements -->
    		<div class="scroller-status" style="display: block;">
    			  <div class="loader-ellips infinite-scroll-request" style="display: none;">
    				<span class="loader-ellips__dot"></span>
    				<span class="loader-ellips__dot"></span>
    				<span class="loader-ellips__dot"></span>
    				<span class="loader-ellips__dot"></span>
    			  </div>
    			  <p class="scroller-status__message infinite-scroll-last" style="display: block;">End of content</p>
    			<div class="scroller-status__message infinite-scroll-error" style="display: none;"><p>No results found</p></div>
    			  
    		</div>
    		<p class="pagination">
    			<?php previous_posts_link( 'Older posts' ); ?>
    			<?php next_posts_link( 'Newer posts' ); ?>
    		</p>
    		<?php wp_reset_postdata(); ?>
    		<?php else: ?>
    		<h2>No search results for: <?php echo get_search_query(); ?></h2>
    		<?php endif; ?>
    
    </div>
    <?php get_footer(); ?>
    
    Thread Starter warwickmusic1

    (@warwickmusic1)

    I think this might be the answer, but again I have no idea where to put this within my code???

    Preserving Search Page Results and Pagination

    <?php
    
    global $query_string;
    
    wp_parse_str( $query_string, $search_query );
    $search = new WP_Query( $search_query );
    
    ?>
    

    I tried replacing the below WP_Query object with the above code but then I get a critical error

    
    	<?php
    	$the_query = new WP_Query ( array(
    		'posts_per_page',
    	));
    	?>
    
    Moderator bcworkz

    (@bcworkz)

    The keyword new means you’re going to have trouble with pagination because you’ve abandoned the default query. It’s possible to get pagination working with a special generic pagination links function, but you’ll still have trouble with infinite scroll.

    You were on the right path with pre_get_posts and the standard WP template. You got stymied by what’s required. That’s OK, but don’t revert to what will not work well. Don’t give up on the correct path because you’re not sure where it goes ??

    Start with this:

    function change_wp_search_size($query) {
        if ( $query->is_search() ) { // Make sure it is a search page
            $query->set('posts_per_page', 10 );
        }
    }
    add_action('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

    Don’t directly access class properties, there are access methods like is_search() and get(). pre_get_posts is an action, no need to return anything. The callback is passed the query by reference, so you’re acting upon the actual query, not a copy like is the usual case.

    Thread Starter warwickmusic1

    (@warwickmusic1)

    Hi @bcworkz

    Thank you for writing back to me again.

    I’m still really struggling to understand some of the terminology in your answer. So, I have your above-mentioned code in my functions.php file.

    Do I need to change anything in this function or is it good as it is?

    function change_wp_search_size($query) {
        if ( $query->is_search() ) { // Make sure it is a search page
            $query->set('posts_per_page', 10 );
        }
    }
    add_action('pre_get_posts', 'change_wp_search_size'); // Hook our custom function onto the request filter

    Then all I have on the search.php file is <?php if (is_search() ) : ?> followed by <?php while ( have_posts() ) : the_post();?>

    Still, I’m only getting 11 results back and the pagination is behaving very weirdly, it currently has a blank page between the results.

    Do I need the pagination to be inside the while?

    I am really confused at this point and I need a more direct answer if possible ??

    Thread Starter warwickmusic1

    (@warwickmusic1)

    I think I’m starting to get to the bottom of this.

    I found this post https://wordpress.stackexchange.com/questions/187961/custom-search-result-page

    If I use the exact code from that example it works, but it renders out posts from all categories.

    So, what makes my code different is the presence of a foreach loop. This foreach is essential because it looks for the category of each post and adds it as a css class so too the wrapper of each post so that the isotope filtering works. There is a variable being set in the while statement that does this.

    Does this sound like I’m in the right ballpark? Any ideas on how I can make this work with a foreach loop?

    Thread Starter warwickmusic1

    (@warwickmusic1)

    Hi @bcworkz

    I’ve definitely found what’s breaking the number of results and the pagination, but I don’t know how to fix it.

    There is a non-WordPress PHP foreach loop wrapped around each post.

    This foreach loop uses 2 different variables. 1 is set by retrieving the slug of the WordPress category each post is placed in using

    
    $termsArray = get_the_terms( $post->ID, "category" );  //Get the terms for this particular item
    $termsString = ""; //initialize the string that will contain the terms
    foreach ( $termsArray as $term ) { // for each term 
    $termsString .= $term->slug.' '; //create a string that has all the slugs 
    }
    

    This variable is then used to add a CSS class to the wrapper of each post using <?php echo $termsString;?>. This is how the first set of filters works, it needs the CSS class being dynamically added like this.

    The second variable is called $color that is set just before the foreach loop starts like this <?php $colors = get_field('content-type');?> it’s using a string set by a custom field added using the Advanced Custom Feilds plugin.

    This second variable is used to set the data-src attribute and also add a CSS class to each post, this is used to do the second set of isotope filtering on the page. I have to be able to add these dynamic attributes to the wrapper elements of the posts.

    Is this going to be possible to do? Will I be able to have a PHP foreach loop inside my if and while statements?

    If not then how do I achieve the same task differently? Will I be able to do this over in the pre_get_posts function in functions.php ?

    • This reply was modified 3 years, 10 months ago by warwickmusic1.
    Thread Starter warwickmusic1

    (@warwickmusic1)

    Hi again @bcworkz

    I really appreciate your help so far with this ??

    I’ve now discovered that the pre_get_posts function in functions.php isn’t actually doing anything. It is being overridden by the “Blog pages show at most” setting in the WordPress dashboard reading settings.

    After further testing, I have narrowed it down to this line of code that is breaking the pagination.

    
    <?php while ( have_posts() ) { the_post(); 
    $termsArray = get_the_terms( $post->ID, "category" );  //Get the terms for this particular item
    $termsString = ""; //initialize the string that will contain the terms
    foreach ( $termsArray as $term ) { // for each term 
    $termsString .= $term->slug.' '; //create a string that has all the slugs 
    }
    ?>

    then

    
    <?php foreach( $colors as $color ): ?>
    <?php $color = strtolower($color); ?>
    <?php $color = str_replace(' ', '-', $color); ?>
    

    (obviously, the foreach loop then closes further down the document.)

    I can’t be 100% sure because the code is too complicated for me to understand, but I do think this also determines that the search results are being retrieved from category 165 which is determined by this line of code further up the document

    
    $terms = get_terms( 'category', array('parent' => 165)); // get all categories, but you can use any taxonomy
    $count = count($terms); //How many are they?
    if ( $count > 0 ){  //If there are more than 0 terms
    foreach ( $terms as $term ) {  //for each term:
    echo "<button class='button btn btn-primary mr-1 mb-1' type='button' data-filter='.".$term->slug."'>" . $term->name . "</button>\n";
    //create a list item with the current term slug for sorting, and name for label
    }
    }
    

    So this foreach loop is doing 2 different things. It’s adding a data-attribute and a CSS class to the wrapper around each post based upon the slug of the WordPress category that the post has been placed in. This is essential for the isotope filtering to work.

    It’s also determined that the results placed on the page should only come from the WordPress post category 165. I think if I can get the pre_get_posts function to work then I could set the category by updating the function to something like

    
    function change_wp_search_size($query) {
        if ( $query->is_search() ) {
            $query->set('posts_per_page', 36 );
    	$query->set('category', 165 );
        }
    
    }
    add_action('pre_get_posts', 'change_wp_search_size');
    

    If I can get the above function to work by overriding the “Blog pages show at most” setting and also for it to display the results from category 165 then I will have got along way into fixing the problem, but I also need the slug of each category added as attributes and I don’t know a different way to do this other than using a PHP foreach loop.

    Please can you tell me exactly how to get the above function to work and please can you help me add the slug of the post’s category as a CSS class to each post (without using a foreach loop if a foreach loop is not possible)?

    Thread Starter warwickmusic1

    (@warwickmusic1)

    Here is the correct function to control the number of post per page in the search results pagination

    // Display 10 results from category 165
    function my_number_of_results($query) {
        if ( $query->is_main_query() && is_search() ) {
            $query->set( 'post_type', 'post' );
    		$query->set( 'posts_per_page', 10 );
    		$query->set( 'category', 165 );
        }
        return $query;
    }
    add_filter( 'pre_get_posts','my_number_of_results' );

    The code now works and the custom results page is returning the correct number of results per page.

    • This reply was modified 3 years, 10 months ago by warwickmusic1.
    • This reply was modified 3 years, 10 months ago by warwickmusic1.
    Moderator bcworkz

    (@bcworkz)

    Sorry for being slow to reply to your posts. So the problem ended up being failure to check is_main_query()? That’s strange, I’d have thought is_search() would only be set for a main query. It may not matter, but it’s more proper to check $query->is_search()

    I don’t see how not checking is_main_query() would fail to influence posts_per_page. Without the check, posts_per_page would then apply to all search queries, (which is maybe a different problem) but the main query should still be affected either way. I suspect caching may have been confusing the results of code changes. At least it’s working now! That’s all that really matters.

    $query->set( 'category', 165 ); is working as well? That’s odd too, according to the docs it should be $query->set( 'cat', 165 );. If either works, I recommend going with the ‘cat’ version.

    There’s no reason a foreach loop would be required instead of a while loop. They are both generic looping structures, the only difference is how the loop terminates. What does matter is how the current post in the loop is managed. As a matter of common practice, the standard WP loop which works on the main query is a while loop. Foreach is commonly used for custom queries made from the template itself. But they could be vice versa if they’re handled correctly.

    Also, having a foreach within a while loop (or any kind of loop) should be fine as long as there is no variable conflict. If one of the foreach loops used $post instead of $term or $color, that could create a problem. As they are, they shouldn’t affect the outer while loop.

Viewing 11 replies - 1 through 11 (of 11 total)
  • The topic ‘How do I write a custom search.php results page’ is closed to new replies.