如何在WP循环内添加循环广告和不同的帖子风格? [英] How to add looping advertisement and different post stlyes inside WP loop?

查看:35
本文介绍了如何在WP循环内添加循环广告和不同的帖子风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个循环,它只查询来自特定类别的帖子并以相同的样式显示它们.我想要的是每 5 个帖子显示一个不同样式的帖子 + 1 个 AdSense 广告,而其他帖子保持相同的样式.例如:1 个大图片帖子 + 1 个广告 + 3 个小帖子.我正在使用无限滚动插件,因此以这种方式使用它会很酷.我仍然是 .php 和 WP 的新手,所以我没有尝试太多,除了一些自定义的 html 和 css 内部循环,这显然不起作用.

So I have this loop which queries posts only from a specific category and displays them with the same style. What I want is to display a different styled post + 1 adsense ad every 5 posts while the others posts keep the same style. Ex: 1 big picture post + 1 ad + 3 small posts. I'm using infinite scroll plugin so it'd be cool to have it this way. I'm still way too newbie at .php and WP so I haven't tried much except for some custom html and css inside to loop, which obviously did not work.

 <?php query_posts("cat=8&paged=$paged&posts_per_page=7"); ?>
 <?php while ( have_posts() ): the_post(); ?>
 <article id="entry-<?php the_ID(); ?>" <?php post_class('entry group'); ?>>
  <div id="postcontent"></div>
 </article>
 <?php endwhile; ?>
 <?php wp_reset_query(); ?>

推荐答案

这里有一个想法:

在循环中添加您的自定义函数或引入您自己的钩子:

Add your custom function or introduce your own hook inside the loop:

<?php while ( have_posts() ): the_post(); ?>

    <article id="entry-<?php the_ID(); ?>" <?php post_class('entry group'); ?>>
         <div id="postcontent"></div>
    </article>

    <?php do_action( 'inject_ads', $wp_query->current_post ); ?> 

<?php endwhile; ?>
<?php wp_reset_query(); ?>

您可以在何处插入您的广告:

where you can inject your ads like this:

add_action( 'inject_ads', function( $i ){

    if( 4 === $i % 5 )
    {
         echo '... your ad code ...';
    }

});

下面的表格显示了这可能是如何工作的:

Here's a table showing how this might work:

i i%5
0  0
1  1
2  2
3  3
4  4  <-- inject ad
5  0
6  1
7  2

在无限滚动的情况下,您可以尝试替换

In the case of an infinite scroller, you could try to replace

    <?php do_action( 'inject_ads', $wp_query->current_post ); ?> 

    <?php do_action( 'inject_ads', $k ); ?> 

哪里

$k = ( $paged > 1 ) ? $wp_query->post_count * ( $paged - 1 ) + $wp_query->current_post : $wp_query->current_post;

保留注射期.

希望这会有所帮助.

Ps:您正在使用 query_posts,但更常见的是使用 pre_get_posts 钩子来修改主查询.

Ps: You're using query_posts, but it's more common to use the pre_get_posts hook to modify the main query.

这篇关于如何在WP循环内添加循环广告和不同的帖子风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆