Blog / WordPress/ How to Insert Ads in WordPress Content Without a Plugin

How to Insert Ads in WordPress Content Without a Plugin

WordPress 教程:无需插件在文章内容中间插入广告代码

Insert Ads in WordPress Content Without a Plugin

By modifying your theme's functions.php file, you can insert ad code (e.g., after the second paragraph) directly into your post content without installing a plugin. This method offers greater flexibility and control over the code.

Implementation Steps

Add the following code to the end of your active theme's functions.php file:

// Insert ad after the second paragraph in single posts
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
    $ad_code = '
Place your ad code here (e.g., Google AdSense)
'; if ( is_single() && ! is_admin() ) { // Change the number 2 to target a different paragraph return prefix_insert_after_paragraph( $ad_code, 2, $content ); } return $content; } // Core function: Insert content after a specific paragraph function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_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 ); }

Code Explanation & Customization

  • Ad Code: Replace the <div>Place your ad code here...</div> placeholder with your own ad HTML or JavaScript.
  • Ad Position: The ad appears after the second paragraph by default. To change this, modify the second argument (2) in the call to prefix_insert_after_paragraph inside the prefix_insert_post_ads function (e.g., use 3 for after the third paragraph).
  • Scope: The is_single() condition ensures the ad only appears on single post pages in the front end, not in the admin area.

Alternative: Using a Plugin

If you prefer not to edit code, you can use a dedicated plugin like Insert Post Ads. Plugins provide a graphical interface for managing multiple ad placements and insertion rules more conveniently.

Important: Always back up your theme files before making changes. If you use a child theme, add the code to the child theme's functions.php to prevent your modifications from being overwritten during theme updates.

Post a Comment

Your email will not be published. Required fields are marked with *.