我在我的wordpress主题中有以下循环,它显示了帖子中所有附加的图像。我想做的是插入一个谷歌广告代码后3个附件在一篇文章。
<?php function show_attachments(){
global $post;
while( have_posts () ){
the_post();
$post_id = $post -> ID
?>
<div class="featimg" >
<div class="img">
<?php
$img_src = wp_get_attachment_image_src( $post_id , 'full' );
echo '<img src="'.$img_src[0].'" alt="" />';
?>
</div>
</div>
<?php
}
}
$layout = new LBSidebarResizer( 'attachment' );
$layout -> render_frontend( 'show_attachments' );
?>
我想我必须做一些类似的事情:
<?php
$i = 0;
function show_attachments(){
global $post;
while( have_posts () ){
$i++;
the_post();
if ($i == 3){
echo 'google ads code here';
};
$post_id = $post -> ID
?>
<div class="featimg" >
<div class="img">
<?php
$img_src = wp_get_attachment_image_src( $post_id , 'full' );
echo '<img src="'.$img_src[0].'" alt="" />';
?>
</div>
</div>
<?php
}
}
$layout = new LBSidebarResizer( 'attachment' );
$layout -> render_frontend( 'show_attachments' );
?>
你们能进一步帮助我吗?
因为在循环中使用了这个,所以不需要使用$post全局变量来获取文章的id。有一个内置函数:
get_the_ID();
对于"if"语句,你只会得到一次回显,因为你看到的是if $i == 3,这只会发生一次。在大多数情况下,这可能适用于您的情况,但如果您有6或9个附件,并且您想在后面插入代码,则行不通。
我建议使用模数运算符,并测试是否$ I % 3 == 0。因此,如果$i除以3没有余数,则回显代码
我的建议是:
function show_attachments(){
$i = 1;
global $post;
while( have_posts () ){
the_post();
if ($i % 3 == 0){
echo 'google ads code here';
};
...
$i++;
}
如果你想保留$post_id变量:
$post_id = get_the_ID();
您已经关闭了它,但我认为您需要将$i
放入函数中:
function show_attachments(){
$i = 0;
global $post;
...