简体   繁体   中英

HTML only print once in Wordpress Loop

I have a code chunk that is inside the_content(); I'm using acf repeater as well. So when I post a blog, I'll either use the_content(); or the acf field. I have h2 tag ( latest articles ) that I only want printed one time, but it's printing everytime I make a post.

<?php if (have_posts()): while (have_posts()) : the_post(); ?>
<div class="container"> 
    <div class="row">
        <div class="col-md-4 sidebar-r">
            <?php echo the_content(); ?>
        </div><!-- end sidebar-r -->
        <?php 
            $i = $wp_query->post_count;
            if($i <=1) {
                echo '<h2 class="link-title">
                        <?php the_sub_field('link_title'); ?>,
                    </h2>';
            }else{
                echo '';
            }

        ?>

        <div class="col-md-8 links-wrap">
            <?php if(have_rows('daily_links')): ?>
                <?php while(have_rows('daily_links')): the_row(); ?>
                <a href="<?php the_sub_field('link_url'); ?>" target="_blank">
                    <h2 class="link-title">
                        <?php the_sub_field('link_title'); ?>,
                    </h2>
                    <h3 class="link-source">
                        <?php the_sub_field('link_source'); ?>
                    </h3>
                </a>
                <?php endwhile; ?>
            <?php endif; ?>
        </div><!-- end links wrap --> 
    </div><!-- end row --> 
</div><!-- end container --> 
<?php endwhile; ?>

<?php else : ?>

<?php endif; ?>

You'll see I tried using php to count the posts and if more than one post, don't print the tag, but couldn't figure out the exact logic and syntax.

I am honestly struggling a bit to understand exactly what you are trying to do and since I do not even have the posts and other key pieces of information so that I can properly replicate your issue so that I can help you better, this is a little bit challenging. That being said, looking into some ideas I came across another stackoverflow question/answer that might be relevant for you in catching the first post and does something to it. The answer to the referenced question instance was this:

<?php if (have_posts()) : $postCount = 1; while (have_posts()) : $postCount++; ?>

<?php if($postCount == 2) { ?>
  // SOMETHING TO DO WITH FIRST POST
<?php } else { ?>
  // SOMETHING TO DO WITH ALL OTHER POSTS
<?php } ?>

This was suggested by user Bora in this answer from 2013 .

Let me know if that helped!

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