如何在WordPress中的列表帖子类别中插入广告

时间:2017-04-27 21:42:35

标签: php wordpress function categories

我想插入adrotate插件生成的广告,我想在特定类别列表中的第三篇帖子之后插入广告,请将以下代码作为示例,我想更改它但不起作用对我来说。

//Insert ads after second paragraph of single post content.

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $adrotate = adrotate_ad(3);

    $ad_code = $adrotate;
    //*ORIGINAL CODE
    /*if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 2, $content );
   }*/
    if ( is_category('Financial') && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 2, $content );
    }

    return $content;
}

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    //*ORIGINAL CODE
    //$closing_p = '</p>';
    $closing_p = '</article>';
    $paragraphs = explode( $closing_p, $content );
    foreach ($paragraphs as $index => $paragraph) {

    if ( trim( $paragraph ) ) {
        $paragraphs[$index] .= $closing_p;
    }

    if ( $paragraph_id == $index + 1 ) {
        $paragraphs[$index] .= $insertion;
    }
}

return implode( '', $paragraphs );
}

Place for the Ad

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我已经解决了它,我分享它以防万一有人帮助,我已经解决了它我分享它以防有人帮助,在文件中使逻辑显示类别的元素列表我添加了以下代码:

//inside loop
//Counts items
$ContItems++ ;

Out loop

<?php
//Print Banner Ad
if ( is_category('Financial') && ! is_admin() ) { ?>
<?php
    if($ContItems == 3){
        echo "<div class='banner-ads'>";
        echo adrotate_ad(3);
        echo "</div>";
    }
?>