Hook midway through the_content();?

Basically, I want to add a function that executes half way through the_content();

I want to add a message/ad block whatever in the middle of all of my content without having to go in to each individual page and add the block.

Read More

Is this even possible?

Related posts

Leave a Reply

2 comments

  1. Use this function ad_content() in replace of the_content() in your template.

    function ad_content() {
    $content = apply_filters ( 'the_content', get_the_content () );
    $content = explode ( "</p>", $content );
    $half_way = ( count($content) / 2);
        for ( $i = 0; $i < count( $content ); $i ++ ) {
            if ( $i == $half_way ) {
                echo 'YOUR_AD_CODE';
    
            }
            echo $content[$i] . "</p>";
        }
    }
    
  2. Of course it’s possible, you’ll just want to write a function that finds the middle of the content then ads your block. Something like this

    function wpse_37015(){
    
    //get the content   
    $content= get_the_content(); //get the content as a variable
    
    // find the middle
    $content_length= STRLEN($content);
    $halfway_mark = ($content_length/ 2);
    
    // clip off the first half
    $firsthalf = SUBSTR($content, 0, $halfway_mark);
    
    // find the last '<br>' in the first half
    $end_mark = STRRPOS($firsthalf, '<br>');
    
    // add in the adblob at the position found above
    
    return SUBSTR($content, 0, $end_mark) . "<p> YOUR AD HERE p>" . SUBSTR($content, $end_mark); 
    }
    
    add_filter('the_content', 'wpse_37015');
    

    This is totally untested and may need to be reworked I got the code to find the middle from here.

    Edit: As OneTrickPoney pointed out we need to check for HTML tags one method may be to use php’s strip_tags() function . and add something like this after the first content call:

    $content = strip_tags($content) //remove html tags
    

    the problem will be adding the tags back at the end.