Terminate loop when URL is found

<?php $the_query = new WP_Query( array('post_type' => 'video', 'posts_per_page' => 1, 'post_status' => 'publish') );	?>
            		<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                    <div class="viframe">
                        <!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/G4Q0oX8wquU" allow="autoplay; encrypted-media" allowfullscreen></iframe> -->
                        <?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
                        <iframe id="vid_frame" width="560" height="315" src="<?php echo str_replace("https://www.youtube.com/watch?v=","https://www.youtube.com/embed/",$url); ?>" allowfullscreen frameborder="0"></iframe>
                    </div>
                    <?php endwhile; endif;?>

The above logic will get the $url from the latest posts, but there is quiet a possibility that the latest posts may not have the URL than I want that it should look for the second latest, or third latest and so on… and as soon as it find sthe URL the loop should terminate.

Some PHP is involved, but I am unable to do this. Please help me.

Try this:

<?php
  declare(strict_types=1);  
  ini_set('display_errors', 'true');
  error_reporting(-1);

  $the_query = new WP_Query(
    array('post_type' => 'video', 
    'posts_per_page'  => 1, 
    'post_status'     => 'publish') 
  );


  if ( $the_query->have_posts() ) : 
    while ( $the_query->have_posts() ) : 
      $the_query->the_post();
?>
    
      <div class="viframe">
        <!-- <iframe width="560" height="315" src="https://www.youtube.com/embed/G4Q0oX8wquU" allow="autoplay; encrypted-media" allowfullscreen></iframe> -->
        <?php $url = esc_url
          ( 
            get_post_meta
            (
              get_the_ID(), 
              'video_oembed', 
              true 
            )
          );
          echo '<br>Before: $url ==> ' .$url;
          $url = str_replace
                 (
                  "https://www.youtube.com/watch?v=", 
                  "https://www.youtube.com/embed/",
                  $url
               ); 
          echo '<br>After: $url ==> ' .$url .'<br>';
        ?>
        <iframe 
          id="vid_frame" 
          width="560" height="315" 
          src="<?= $url ?>" allowfullscreen frameborder="0"
        ></iframe>
 
      </div>

<?php 
    endwhile; 
  endif;
?>

1 Like

Tried not working.

Not very helpful :frowning:

Were there any errors or warnings?

What was the output?

What did you expect?

Edit:
If you want to break out of the while loop add this condition:

</php
   //

 while ( $the_query->have_posts() ) : 
    // do your stuff here before possible break
       if( $condition === TRUE):
         break;
       endif;
    // or do your stuff here	after the possible break
 endwhile; 

3 Likes

what will be the condition →

   if( $condition === TRUE):

?

from your original post

and as soon as it find sthe URL the loop should terminate.

The request is vague because it does not specify the matching URL to test against the looped URLs.

More explicit information is required.

1 Like
<?php
    $the_query = new WP_Query( array(
        'post_type' => 'video',
        'posts_per_page' => 1,
        'post_status' => 'publish'
    ) );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
<?php endwhile; endif;?>

I want that loop should run until it finds a first valid non-empty $url that means as soon as it finds a valid $url the loop should terminate. It should keep running until it finds the first valid non-empty URL.

How should we condition it to get what i want?

N.B. → Loop should work from the latest post to the oldest post.

Valid URL means it has a video URL such as youtube, vimeo etc.

This worked →

<?php $the_query = new WP_Query( array('post_type' => 'video', 'posts_per_page' => 10, 'post_status' => 'publish') );	?>
            		<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                        <?php $url = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) ); ?>
                        <?php $embed = wp_oembed_get( $url ); ?>
                        <?php if( $embed ) {wp_reset_query();} ?>
                    <?php endwhile; endif;?>

But it actually is fetching the URL of the oldest post.

Is that not a valid URL as you stated you wanted the code to do?

1 Like

If the oldest post is showing first then it could be changed by adding ORDER BY DESC to the SQL Query;

https://dev.mysql.com/doc/refman/8.0/en/sorting-rows.html

[offtopic]
Why are you repeatedly opening and closing PHP?
It is far more readable to just open PHP once and even better to echo HTM: scripts.
Or is it just me that has difficulty reading your scripts?
[/offtopic]

<?php
  declare(strict_types=1);
  ini_set('display_errors', 'true');
  error_reporting(-1);

  $the_query = new WP_Query
  ( 
	array
	(
		'post_type'      => 'video', 
		'posts_per_page' => 10, 
		'post_status'    => 'publish'
	) 
);	

  if ( $the_query->have_posts() ) : 
	while ( $the_query->have_posts() ) : 
		$the_query->the_post(); 
		$url   = esc_url( get_post_meta( get_the_ID(), 'video_oembed', true ) );
        $embed = wp_oembed_get( $url ); 
     	if( $embed ):
			wp_reset_query();
        endif;	 
    endwhile; 
  endif;


**Edit:** Fourmatting and spelling not my forty :)
1 Like

I will update this shortly with full comprehensive details. Thanks!

Is that coding practice wrong? I learned PHP from lynda.com, sitepoint.com, and udemy.com, and many WP authors were doing it like this only.

http://aristath.github.io/kirki/docs/controls/checkbox.html → This one, for example, =
https://www.screencast.com/t/v1EJ1TwaV

That example has HTML code between each line of PHP. Yours does not. In your example code in post #8, the continual opening and closing on each line is not required because all that code is PHP. All it really does is make it harder to read.

Sure, when you’re needing to send HTML out, then you either have to come “out” of PHP to do it, or use echo() and have your PHP output it, and the choice will depend on the exact circumstances.

2 Likes

I think using PHP is:

  1. more readable
  2. less chance of syntax errors
  3. less script involved
  4. reduces processing overhead
  5. easy to echo PHP variables within a HTML statement
  6. repeat PHP blocks can usually be replaced with a function call or included from a PHP file
  7. PHP processing is server side and only HTML text is sent to a browser
  8. PHP server validation catches most errors and warnings before outputting results
  9. PHP result script easily minified which reduces browser rendering time
1 Like

I will take care while coding in the future. Thanks!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.