Saturday, January 6, 2024
HomeMobile MarketingWordPress: How To Insert An Advert Slot Midway Into A Web page...

WordPress: How To Insert An Advert Slot Midway Into A Web page Or Publish


For those who’ve been searching my website this week, you may even see some adverts that don’t fairly match proper. I’m engaged on getting every part working appropriately and have most of it corrected. I’m doing this to extend monetization on the positioning quite than being depending on Google Adsense and clogging your view of the content material with pushy and obnoxious promoting.

One of many suggestions that was made to me was to insert an commercial midway by a weblog publish or web page content material. Whereas that sounds simple, it might probably wreak havoc with column layouts or breaking apart paragraphs. It’s not so simple as including the whole characters, dividing by two, and inserting the advert code. There are some further exceptions:

  • Headings – I don’t need an advert to observe a heading.
  • Paragraphs I would like adverts to be inserted after a paragraph is accomplished.
  • Columns – I don’t need adverts to be inserted inside a column.

To do that, I added a perform to features.php in my youngster theme to insert the advert slot inside a web page or publish with the next code:

perform insert_ad_in_middle_of_content( $content material ) {
    // Solely run this on single posts/pages
    if ( is_single() || is_page() ) {
        $closing_p = '</p>';
        $block_columns_class="wp-block-columns";

        // Break up content material to seek out the center
        $halfway_mark = strlen( $content material ) / 2;
        $first_half = substr( $content material, 0, $halfway_mark );
        $second_half = substr( $content material, $halfway_mark );

        // Modify for wp-block-columns
        if (strpos($first_half, '<div class="' . $block_columns_class . '">') !== false &&
            substr_count($first_half, '<div class="' . $block_columns_class . '">') > substr_count($first_half, '</div>')) {
            $end_of_block_columns = strpos($second_half, '</div>') + strlen('</div>');
            $first_half .= substr($second_half, 0, $end_of_block_columns);
            $second_half = substr($second_half, $end_of_block_columns);
        }

        // Discover a appropriate place for the advert
        $suitable_place_found = false;
        whereas (!$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);
                // Verify if the paragraph is straight away preceded by a heading tag
                if (!preg_match("/<h[1-6]>.*</h[1-6]>$/", $substring_before_p)) {
                    $suitable_place_found = true;
                } else {
                    // Transfer previous this paragraph and proceed looking out
                    $second_half = substr($second_half, $position_of_p + strlen($closing_p));
                }
            } else {
                // No extra paragraphs, exit the loop
                break;
            }
        }

        // Insert advert code
        $ad_code="<!-- Advert Code Right here -->";
        if ($suitable_place_found) {
            $second_half = substr_replace($second_half, $ad_code, $position_of_p, 0);
        } else {
            // Fallback: Append advert on the finish of the content material
            $second_half .= $ad_code;
        }

        // Reassemble content material
        $content material = $first_half . $second_half;
    }

    return $content material;
}

add_filter( 'the_content', 'insert_ad_in_middle_of_content' );

Right here’s an in depth walk-through of the insert_ad_in_middle_of_content perform, explaining every half step-by-step:

  1. Operate Definition:
perform insert_ad_in_middle_of_content( $content material ) {

This line defines a perform named insert_ad_in_middle_of_content that takes one argument, $content material. This argument represents the content material of a publish or web page.

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

The perform first checks if the present request is for a single publish or a web page utilizing is_single() and is_page() features. The advert insertion logic will solely run if this situation is true. For those who’d like to incorporate customized publish sorts, you’ll be able to add them as nicely:

perform insert_ad_in_middle_of_content( $content material ) {
    $current_post_type = get_post_type();

    // Verify for single normal posts, pages, or customized publish sorts
    if ( is_single() || is_page() || $current_post_type == 'my_custom_post_type' ) {
        // ... remainder of the code stays the identical
    }

    return $content material;
}

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

Right here, two variables are outlined. $closing_p holds the closing paragraph tag </p>. $block_columns_class is a string representing a CSS class that WordPress makes use of for block columns.

  1. Discovering the Midway Mark:
$halfway_mark = strlen( $content material ) / 2;
$first_half = substr( $content material, 0, $halfway_mark );
$second_half = substr( $content material, $halfway_mark );

The content material’s size is halved to discover a tough halfway level. The content material is then cut up into two halves at this level.

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

This block of code checks if there are any unclosed wp-block-columns divs within the first half of the content material. If there are, it adjusts the cut up level to make sure the advert isn’t inserted inside a block column.

  1. Discovering a Appropriate Place for the Advert:
whereas (!$suitable_place_found) {
   ...
}

This whereas loop searches for an appropriate place to insert the advert within the second half of the content material. It appears for a paragraph ending (</p>) that isn’t instantly preceded by a heading tag. If such a place is discovered, $suitable_place_found is ready to true.

  1. Inserting the Advert Code:
$ad_code="<!-- Advert Code Right here -->";
if ($suitable_place_found) {
   ...
} else {
   ...
}

Right here, the precise advert code (represented by <!-- Advert Code Right here -->) is ready. If an appropriate place was discovered, the advert code is inserted at that place within the second half of the content material. If not, as a fallback, the advert code is appended to the top of the second half.

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

After inserting the advert, the primary and second halves of the content material are concatenated again collectively.

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

The modified content material, now with the advert inserted, is returned.

  1. Including the Filter:
    php add_filter( 'the_content', 'insert_ad_in_middle_of_content' );
    Lastly, the perform is hooked to the the_content filter. This tells WordPress to run this perform on the content material of posts and pages, permitting the perform to change the content material earlier than it’s displayed on the positioning.

This code is beneficial for dynamically putting adverts throughout the content material, doubtlessly rising engagement and income. Utilizing a fallback mechanism ensures that adverts will at all times be displayed, maximizing the chance for advert views and clicks even when an appropriate location isn’t discovered with the logic above.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments