Check if first paragraph is an image, then show custom code right after it?

I would like to add some code in functions.php that does this:

  • If the first paragraph contains an image, show my custom code right AFTER it. For example:

    <div class="entry-content">
        <p><img src="https://example.com/example.jpg" alt="Image in 1st para" /></p>
        <div>MY CUSTOM CODE</div>
    </div>
    
  • But if the first paragraph is text (i.e. NOT an image), show my custom code right BEFORE it.

    <div class="entry-content">
        <div>MY CUSTOM CODE</div>
        <p>This 1st paragraph contains text, not an image.</p>
    </div>
    

How do I do it? An example code snippet is most welcome.

PS: The custom code could also be an ad (e.g. Google Adsense).

3 s
3

How about a few simple lines With jQuery?

jQuery(document).ready( function ($) {
    if ($(".entry-content:first-child").has('img').length) //this check for the img tag
        $(".entry-content:first-child").after("<div>MY CUSTOM CODE</div>");
    else
        $(".entry-content:first-child").before("<div>MY CUSTOM CODE</div>");
});

Update:

Here is a simple solution using php’s native DOMDocument

add_filter('the_content','add_code_before_afterImage');

function add_code_before_afterImage($content){
    $MYCODE = '<div>this is my custom code</div>';
    $doc = new DOMDocument();
    @$doc->loadHTML('<?xml encoding="'.get_bloginfo('charset').'">'.$content);
    $ps = $doc->getElementsByTagName('p');
    foreach ($ps as $p) {
        if (false !== stripos($p->nodeValue,'img'));
            return str_replace($p->nodValue, $p->nodValue.$MYCODE, $content);
        }
        break;
    }
    //if we got here then there is no img tag in the first paragraph
    //so we return the code before the content.
    return $MYCODE.$content;
}

Update 2:

@Sarathi’s comment go me thinking the you don’t actually need to parse any part of the content just pull the first paragraph and check if it has an img tag so here is a simpler and by far faster solution using just PHP’s native str_replace and stripos

add_filter('the_content','simple_img_tag_search');
function simple_img_tag_search($content){

    $MYCODE = '<div>this is my custom code</div>';

    //split content to first paragraph and the rest
    $paragraphs = explode( '</p>', $content, 2 );

    //extract the first paragraph
    $first_paragraph = $paragraphs[0];

    //then just look for img tag
    if (false === stripos($first_paragraph, "<img")){
        //not found then just return the code before the content
        return $MYCODE.$content;
    }else{
        // img tag found so we return the code after the first paragraph
        return str_replace($first_paragraph.'</p>',$first_paragraph.'</p>'.$MYCODE,$content);
    }
}

Leave a Comment