Как вставить <div>после каждых 5 сообщений в цикле WordPress, который бесконечно загружается? - PullRequest
0 голосов
/ 05 марта 2019

Итак, у меня настроен цикл WPQuery, который прекрасно работает, использует бесконечную прокрутку, чтобы загружать посты партиями по 10 постов.Что я хотел бы сделать, это вставить <div> после каждого 5-го поста в списке.Я добавил код счетчика, но он, похоже, не дает желаемого результата.Вот код:

<?php
   $featuredPosts = get_field('featured_posts');
   $excludePosts = [];
   foreach($featuredPosts as $key => $postItem) {
      $excludePosts[] = $postItem->ID;
   }

  $numPosts = 10;
  $args = array(
    'post_type'  => 'post',
    'post_status' => 'publish',
    'posts_per_page' => $numPosts,
    'post__not_in' => $excludePosts
  );


  $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
      $counter = 0;
      while ( $the_query->have_posts() ) {
        $the_query->the_post();
?>
        <article id="post-<?php echo get_the_ID(); ?>" <?php post_class('frontpage-articles'); ?> >
            <div class="entry-container">
                <div class="post-meta"><span class="entry-date"><?php echo get_the_date("M d, Y", get_the_ID()); ?></span>
                    <span class="entry-author">by
                       <a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))) ?>"><?php the_author(); ?></a>
                    </span>
                </div>
                <header class="entry-header">
                    <h3 class="entry-title">
                        <?php echo sanitize_title(the_title( '<a href="' . esc_url(get_permalink($post->ID) ) . '">', '</a>' )); ?></h3>
                </header><!-- .entry-header -->

                <div class="entry-summary">
                    <?php /*echo substr(strip_tags(get_the_excerpt()), 0,999); */?>
                    <?php echo substr(strip_tags(get_the_excerpt()), 0, 120); ?>
                </div><!-- .entry-summary -->
            </div>
            <!-- #thumbnail-->
            <?php
            $cloudinaryImage = get_post_meta($post->ID, 'cloudinary_image_id');
            if ( has_post_thumbnail() ) {
                $thumbnailUrl = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
            }
            ?>

            <?php
            $thumbnail = '';
            if(!empty($cloudinaryImage[0])) {
                $thumbnail = "https://res.cloudinary.com/upload/".$cloudinaryImage[0];
            } else if(!empty($thumbnailUrl)) {
                $thumbnail = $thumbnailUrl[0];
            } ?>
            <a href="<?php echo esc_url(get_permalink($post->ID))?> ">
                <div class="entry-thumb" style="background-image: url('<?= $thumbnail; ?>'); background-repeat: no-repeat; background-size: cover;" alt="">
                </div>
            </a>
            <!-- .thumbnail-image -->
        </article>
            <?php 
                if ($counter % 5 == 0){
                  echo '<div>Ads Test Div to Be inserted after every 5th post</div>';
                }
                $counter++;
            ?>
        <hr>
        <?php

    }
    /* Restore original Post Data */
    wp_reset_postdata();
}

Я не вижу, что не так с количеством?Я считаю, что это в правильном месте.Любая помощь определенно будет оценена.

1 Ответ

0 голосов
/ 05 марта 2019

Ваш $ counter ++;после if ($ counter% 5 == 0).Вы должны переместить $ counter ++;выше, если, потому что $ counter нужно увеличить значение перед делением.

Попробуйте этот код:

<?php
   $featuredPosts = get_field('featured_posts');
   $excludePosts = [];
   foreach($featuredPosts as $key => $postItem) {
      $excludePosts[] = $postItem->ID;
   }

  $numPosts = 10;
  $args = array(
    'post_type'  => 'post',
    'post_status' => 'publish',
    'posts_per_page' => $numPosts,
    'post__not_in' => $excludePosts
  );


  $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) {
      $counter = 0;
      while ( $the_query->have_posts() ) {
        $the_query->the_post();
?>
        <article id="post-<?php echo get_the_ID(); ?>" <?php post_class('frontpage-articles'); ?> >
            <div class="entry-container">
                <div class="post-meta"><span class="entry-date"><?php echo get_the_date("M d, Y", get_the_ID()); ?></span>
                    <span class="entry-author">by
                       <a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))) ?>"><?php the_author(); ?></a>
                    </span>
                </div>
                <header class="entry-header">
                    <h3 class="entry-title">
                        <?php echo sanitize_title(the_title( '<a href="' . esc_url(get_permalink($post->ID) ) . '">', '</a>' )); ?></h3>
                </header><!-- .entry-header -->

                <div class="entry-summary">
                    <?php /*echo substr(strip_tags(get_the_excerpt()), 0,999); */?>
                    <?php echo substr(strip_tags(get_the_excerpt()), 0, 120); ?>
                </div><!-- .entry-summary -->
            </div>
            <!-- #thumbnail-->
            <?php
            $cloudinaryImage = get_post_meta($post->ID, 'cloudinary_image_id');
            if ( has_post_thumbnail() ) {
                $thumbnailUrl = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );
            }
            ?>

            <?php
            $thumbnail = '';
            if(!empty($cloudinaryImage[0])) {
                $thumbnail = "https://res.cloudinary.com/upload/".$cloudinaryImage[0];
            } else if(!empty($thumbnailUrl)) {
                $thumbnail = $thumbnailUrl[0];
            } ?>
            <a href="<?php echo esc_url(get_permalink($post->ID))?> ">
                <div class="entry-thumb" style="background-image: url('<?= $thumbnail; ?>'); background-repeat: no-repeat; background-size: cover;" alt="">
                </div>
            </a>
            <!-- .thumbnail-image -->
        </article>
            <?php 
                $counter++;
                if ($counter % 5 == 0){
                  echo '<div>Ads Test Div to Be inserted after every 5th post</div>';
                }

            ?>
        <hr>
        <?php

    }
    $counter = 0;
    /* Restore original Post Data */
    wp_reset_postdata();
}
 echo do_shortcode('[ajax_load_more preloaded="false"  offset="13"  exclude"="'.implode(",", $excludePosts).'" images_loaded="false" button_label="Load more" transition_container="false" progress_bar="false" posts_per_page="10" pause="true" pause_override="true" css_classes="infinite-scroll"]');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...