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

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