Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

WordPress: How To Insert An Ad Slot Halfway Into A Page Or Post

If you’ve been browsing my site this week, you may see some ads that don’t quite fit right. I’m working on getting everything working correctly and have most of it corrected. I’m doing this to increase monetization on the site rather than being dependent on Google Adsense and clogging your view of the content with pushy and obnoxious advertising.

One of the recommendations that was made to me was to insert an advertisement halfway through a blog post or page content. While that sounds easy, it can wreak havoc with column layouts or breaking up paragraphs. It’s not as simple as adding the total characters, dividing by two, and inserting the ad Code. There are some additional exceptions:

  • Headings – I don’t want an ad to follow a heading.
  • Paragraphs I want ads to be inserted after a paragraph is completed.
  • Columns – I don’t want ads to be inserted within a column.

To do this, I added a Function to functions.php in my child theme to insert the ad slot within a page or post with the following code:

function insert_ad_in_middle_of_content( $content ) {
    // Only run this on single posts/pages
    if ( is_single() || is_page() ) {
        $closing_p = '';
        $block_columns_class = 'wp-block-columns';

        // Split content to find the middle
        $halfway_mark = strlen( $content ) / 2;
        $first_half = substr( $content, 0, $halfway_mark );
        $second_half = substr( $content, $halfway_mark );

        // Adjust for wp-block-columns
        if (strpos($first_half, '
') !== false && substr_count($first_half, '
') > substr_count($first_half, '
')) { $end_of_block_columns = strpos($second_half, '
') + strlen('
'); $first_half .= substr($second_half, 0, $end_of_block_columns); $second_half = substr($second_half, $end_of_block_columns); } // Find a suitable place for the ad $suitable_place_found = false; while (!$suitable_place_found) { $position_of_p = strpos($second_half, $closing_p); if ($position_of_p !== false) { $substring_before_p = substr($second_half, 0, $position_of_p); // Check if the paragraph is immediately preceded by a heading tag if (!preg_match("/.*$/", $substring_before_p)) { $suitable_place_found = true; } else { // Move past this paragraph and continue searching $second_half = substr($second_half, $position_of_p + strlen($closing_p)); } } else { // No more paragraphs, exit the loop break; } } // Insert ad code $ad_code = ''; if ($suitable_place_found) { $second_half = substr_replace($second_half, $ad_code, $position_of_p, 0); } else { // Fallback: Append ad at the end of the content $second_half .= $ad_code; } // Reassemble content $content = $first_half . $second_half; } return $content; } add_filter( 'the_content', 'insert_ad_in_middle_of_content' );

Here’s a detailed walk-through of the insert_ad_in_middle_of_content function, explaining each part step-by-step:

  1. Function Definition:
function insert_ad_in_middle_of_content( $content ) {

This line defines a function named insert_ad_in_middle_of_content that takes one argument, $content. This argument represents the content of a post or page.

  1. Condition for Single Posts/Pages:
if ( is_single() || is_page() ) {

The function first checks if the current request is for a single post or a page using is_single() and is_page() functions. The ad insertion logic will only run if this condition is true. If you’d like to include custom post types, you can add them as well:

function insert_ad_in_middle_of_content( $content ) {
    $current_post_type = get_post_type();

    // Check for single standard posts, pages, or custom post types
    if ( is_single() || is_page() || $current_post_type == 'my_custom_post_type' ) {
        // ... rest of the code remains the same
    }

    return $content;
}

add_filter( 'the_content', 'insert_ad_in_middle_of_content' );
  1. Variable Definitions:
$closing_p = '';
$block_columns_class = 'wp-block-columns';

Here, two variables are defined. $closing_p holds the closing paragraph tag

. $block_columns_class is a string representing a CSS class that WordPress uses for block columns.
  1. Finding the Halfway Mark:
$halfway_mark = strlen( $content ) / 2;
$first_half = substr( $content, 0, $halfway_mark );
$second_half = substr( $content, $halfway_mark );

The content’s length is halved to find a rough midway point. The content is then split into two halves at this point.

  1. Adjusting for Block Columns:
if (...) {
   ...
}

This block of code checks if there are any unclosed wp-block-columns divs in the first half of the content. If there are, it adjusts the split point to ensure the ad isn’t inserted inside a block column.

  1. Finding a Suitable Place for the Ad:
while (!$suitable_place_found) {
   ...
}

This while loop searches for a suitable place to insert the ad in the second half of the content. It looks for a paragraph ending (

) that isn’t immediately preceded by a heading tag. If such a position is found, $suitable_place_found is set to true.
  1. Inserting the Ad Code:
$ad_code = '';
if ($suitable_place_found) {
   ...
} else {
   ...
}

Here, the actual ad code (represented by ) is set. If a suitable place was found, the ad code is inserted at that position in the second half of the content. If not, as a fallback, the ad code is appended to the end of the second half.

  1. Reassembling the Content:
$content = $first_half . $second_half;

After inserting the ad, the first and second halves of the content are concatenated back together.

  1. Returning the Modified Content:
return $content;
}

The modified content, now with the ad inserted, is returned.

  1. Adding the Filter:
    php add_filter( 'the_content', 'insert_ad_in_middle_of_content' );
    Finally, the function is hooked to the the_content filter. This tells WordPress to run this function on the content of posts and pages, allowing the function to modify the content before it is displayed on the site.

This code is useful for dynamically placing ads within the content, potentially increasing engagement and revenue. Using a fallback mechanism ensures that ads will always be displayed, maximizing the opportunity for ad views and clicks even if a suitable location isn’t found with the logic above.

©2024 DK New Media, LLC, All rights reserved.

Originally Published on Martech Zone: WordPress: How To Insert An Ad Slot Halfway Into A Page Or Post



This post first appeared on How To Optimize Prestashop For Increased SEO And Conversions, please read the originial post: here

Share the post

WordPress: How To Insert An Ad Slot Halfway Into A Page Or Post

×

Subscribe to How To Optimize Prestashop For Increased Seo And Conversions

Get updates delivered right to your inbox!

Thank you for your subscription

×