How to Insert Ads Code in post without any plugin?

Hello Developers, Greetings of the day!

Here you can find quick code for how to insert Ads code in post page.

Please first add the code in theme’s function.php file.

Code is as Below:

add_filter('the_content', 'single_ad_content');

function single_ad_content($content)
{
    if (!is_single()) return $content;
    $afterparagraph = 3; //Enter number of paragraphs to display ad after.
    $content = explode("</p>", $content);
    $new_content = '';
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $afterparagraph) {
            $new_content.= '<div style="width: 100%; height: 250px; padding: 6px 6px 6px 0; float: left; margin-left: 0; margin-right: 18px;">';
            $new_content.= '//Enter your ad code here....';
            $new_content.= '</div>';
        }

        $new_content.= $content[$i] . "</p>";
    }

    return $new_content;
}

After added you can see the post page it will display Ads code there.

 $afterparagraph = 3; //Enter number of paragraphs to display ad after.

You can the change the paragraph no here as per you want. now we have kept the no 3. so it’s mean it will display ads code after the paragraph no 3.

$new_content.= '<div style="width: 100%; height: 250px; padding: 6px 6px 6px 0; float: left; margin-left: 0; margin-right: 18px;">';
            $new_content.= '//Enter your ad code here....';
            $new_content.= '</div>';
        }

In this you can add the Ads code. and if you don’t need HTML div; then you can easily remove it.

I hope article is very useful.

Thank you and Keep growing!! 🙂

Blog Catagory : WORDPRESS