首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Wordpress循环中的文章之间插入自定义代码?

如何在Wordpress循环中的文章之间插入自定义代码?
EN

Stack Overflow用户
提问于 2021-05-15 23:33:40
回答 2查看 52关注 0票数 0

现在我有一个非常基本的Wordpress循环:

代码语言:javascript
复制
<?php 

// get posts
$posts = get_posts(array(
    'post_type'         => 'page',
    'posts_per_page'    => 30,
    'order'             => 'DESC'
));

if( $posts ): ?>

<?php foreach( $posts as $post ): 
        
setup_postdata( $post )
        
        ?>
        
    
<?php the_title(); ?>
    

<?php endforeach; ?>
    
<?php wp_reset_postdata(); ?>

<?php endif; ?> 

基本上我是想在帖子之间插个广告。

并且有一个选项可以指定广告代码会出现在多少个帖子之后。

所以,如果我键入3,那么它看起来是这样的:

代码语言:javascript
复制
Post 1 title

Post 2 title

Post 3 title

AD

Post 4 title

Post 5 title

Post 6 title

AD

...

在另一个类似的线程中,我发现我可以使用计数器来做到这一点:

$i = 1;

代码语言:javascript
复制
if($i==3||$i==5||$i==10){
            /*Adsence here*/
            }

$i++;

但我不知道如何将其实现到我的代码中。

不是编码器,只是想把东西组合起来。

谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-05-16 04:04:31

您可以初始化计数器,将其设置为零,并在每个循环后添加一个计数器。然后,您可以检查计数器的当前值,并在计数器达到一定值时执行操作。

代码语言:javascript
复制
<?php 

// get posts
$posts = get_posts(array(
    'post_type'         => 'page',
    'posts_per_page'    => 30,
    'order'             => 'DESC'
));

$counter = 0;

if( $posts ): ?>

<?php foreach( $posts as $post ): 
        
setup_postdata( $post )     
?>
          
<?php the_title(); ?>

<?php 
// checks if $counter exists in the array
if (in_array($counter, array(3, 6, 9))) {
    // do something when $counter is equal to 3, 6, or 9
    // such as rendering an ad
}

$counter++;
?>

<?php endforeach; ?>
    
<?php wp_reset_postdata(); ?>

<?php endif; ?>  
票数 1
EN

Stack Overflow用户

发布于 2021-05-16 04:10:39

你可以用多种方式设置它。例如,可以在循环中使用current_post获取当前循环索引:

代码语言:javascript
复制
$posts = new wp_query(
  array(
    'post_type'         => 'page',
    'posts_per_page'    => 30,
    'order'             => 'DESC'
  )
);

if( $posts ):

  while($posts->have_posts())
  {

    $posts->the_post();

    $current_post = $posts->current_post; // starts from zero

    if($current_post == 2 || $current_post == 4 || $current_post == 9):?>

      <div>YOUR ADSENCE</div>

    <?php

    endif;

    ?>

    <h3><?php the_title(); ?></h3>

  <?php 
  }

endif;

或者,如果您想使用counter,那么您可以这样做:

代码语言:javascript
复制
$posts = new wp_query(
  array(
    'post_type'         => 'page',
    'posts_per_page'    => 30,
    'order'             => 'DESC'
  )
);

if( $posts ):

  $i = 1; // starts from one OR you could change it to zero to starts from zero if you want to

  while($posts->have_posts())
  {

    $posts->the_post();

    if($i == 3 || $i == 5 || $i == 10):?>

      <div>YOUR ADSENCE</div>

    <?php

    endif;

    ?>

    <h3><?php the_title(); ?></h3>

  <?php 

  $i++;

  }

endif;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67552049

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档