1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Fuctions.php Help

Discussion in 'PHP & Perl' started by sunbros, Nov 9, 2015.

  1. sunbros

    sunbros Regular Member

    Joined:
    Apr 14, 2010
    Messages:
    379
    Likes Received:
    125
    Hey guys,
    I'm using this code to show an ad after 8th paragraph. I don't want it to display ad, if there is less than 8 paragraphs. How can i do that?
    Thanks in advance.


    Code:
    //Insert ads after paragraph of single post content.
    
    
    add_filter( 'the_content', 'prefix_insert_post_ads' );
    
    function prefix_insert_post_ads( $content ) {
            $ad_code = 'paste ad code here';
              if ( is_single() && ! is_admin() ) {
            return prefix_insert_after_paragraph( $ad_code, 8, $content );
        }
        
        return $content;
    }
     
    // Parent Function that makes the magic happen
     
    function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
        $closing_p = '</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 );
    }
    
    
    
     
  2. mantic0re

    mantic0re Junior Member

    Joined:
    May 29, 2015
    Messages:
    118
    Likes Received:
    9
    Wouldn't say this is clean coding but it works for your case.

    Code:
    [COLOR=#cc7832][B]function [/B][/COLOR][COLOR=#ffc66d]showAd[/COLOR]([COLOR=#9876aa]$content[/COLOR]) {
        [COLOR=#9876aa]$closing_p [/COLOR]= [COLOR=#6a8759]'</p>'[/COLOR][COLOR=#cc7832];
        [/COLOR][COLOR=#9876aa]$paragraphs [/COLOR]= explode( [COLOR=#9876aa]$closing_p[/COLOR][COLOR=#cc7832], [/COLOR][COLOR=#9876aa]$content [/COLOR])[COLOR=#cc7832];
        [/COLOR][COLOR=#cc7832][B]if[/B][/COLOR](count([COLOR=#9876aa]$paragraphs[/COLOR]) >= [COLOR=#6897bb]8[/COLOR]) {
            [COLOR=#cc7832][B]echo [/B][/COLOR][COLOR=#6a8759]'PUT AD HTML HERE'[/COLOR][COLOR=#cc7832];
        [/COLOR]}
    
    }