简体   繁体   中英

Hide "foreach" results if there is only one result

I have post type with an "email" custom field. When editing a post, I would like to know if other posts have the same email value.

function samemailaddress($field){ 
    
$emailcurrentpost = get_field('email');
$referencecurrentpost = get_field('reference');
    
    echo '<table>';

global $post;
$tmp_post = $post;
$args = array( 
        'post_type' => 'reservation',
        'posts_per_page' => '-1',);
$myposts = get_posts( $args );

    foreach( $myposts as $post ) : setup_postdata($post);
    
            $reference = get_field('reference');
            $email = get_field('email');

    
        if($email === $emailcurrentpost) {
            ?>
    <tr>
  <td><?php echo $reference; ?></td>
  </tr>
    
<?php   }
        
endforeach;
$post = $tmp_post;

echo '</table>';

 } 

Why not prevent your existing post from coming back in the $myposts query...

$args = array( 
  'post_type' => 'reservation',
  'posts_per_page' => '-1',
  'exclude' => [$tmp_post->ID]
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM