【问题标题】:Insert google ads after certain item counts in a wordpress post在 wordpress 帖子中的某些项目计数后插入谷歌广告
【发布时间】:2015-09-09 20:17:19
【问题描述】:

我的 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' );
?>

你们能帮我进一步吗?

【问题讨论】:

  • 那么你的代码有什么问题?
  • 它不起作用,看起来这不是我正在寻找的正确循环。我找不到带有正确循环的正确文件,用于在单个 wordpress 帖子中显示附加图像。任何想法如何找到它?
  • 这怎么行不通?这是否会显示帖子,但不会与您的谷歌广告相呼应?还是循环中断了,没有帖子显示?
  • 看来这不是在我的帖子中显示图像的循环。即使我在没有任何条件的情况下在函数中放置了一个 ech“测试”,它也不会出现在我的页面上。

标签: php wordpress loops insert ads


【解决方案1】:

由于您在循环中使用它,因此不需要 $post 全局变量来获取帖子的 id。有一个内置函数:

get_the_ID();

使用“if”语句,您只会得到一个回声,因为您看到 if $i == 3 只会发生一次。这在大多数情况下可能适用于您的情况,但如果您有六个或九个附件并且您想在之后插入代码,则它不会起作用。

我建议改用模数运算符并测试 $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();

否则,删除该行并将所有实例更改为该函数。

【讨论】:

    【解决方案2】:

    你对它关闭了,但我认为你需要将 $i 放在函数中:

    function show_attachments(){
        $i = 0;
        global $post;
    ...
    

    【讨论】:

    • 那也不起作用,看来我正在使用的 .php 文件不是正确的。我需要找到文件是在帖子中显示附加图像的循环。很难,几乎打开了所有文件:S 有什么想法吗?
    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多