如何将广告代码插入wordpress帖子

时间:2014-03-20 05:49:04

标签: wordpress-plugin wordpress

我想在第一段之后或之前将广告代码插入WordPress帖子(详细信息页面)。像this post那样有任何插件或任何想法..

2 个答案:

答案 0 :(得分:0)

您可以尝试使用插件Ad Inserter

或者使用此WPBeginner tutorial中的示例:

<?php 
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {

    $ad_code = '<div>Ads code goes here</div>';

    if ( is_single() && ! is_admin() ) {
        return prefix_insert_after_paragraph( $ad_code, 2, $content );
    }

    return $content; 
}

// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
    $closing_p = '</p>';
    $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 );
}

答案 1 :(得分:0)

以下是在WordPress帖子内容中随机显示广告的代码 -

//Insert ads between first and fourth paragraph of single post content to show it randomly between first and second paragraph.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
 // Add code for mobile
 $ad_code_mobile = 'AD CODE FOR MOBILE';
 // Add code for PC
 $ad_code_pc = 'AD CODE FOR PC/DESKTOP/LAPTOP';

 if ( is_single() && ! is_admin() ) {
 if (!wp_is_mobile()) {
 $randnumpc = mt_rand(1,4);
 return prefix_insert_after_paragraph( $ad_code_pc, $randnumpc, $content );
 }
 else {
 $randnummobi = mt_rand(1,4);
 return prefix_insert_after_paragraph( $ad_code_mobile, $randnummobi, $content );
 }
 }
 return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
 $closing_p = '</p>';
 $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 );
}

该代码将在第1和第4段中随机显示广告。您可以将此代码放在主题的functions.php的末尾,也可以为此创建单独的插件。

来源:https://www.eyeswift.com/random-ad-code-in-wordpress-post-content-without-plugin/