0

I need to add a div before the first paragraph.

Example:

<div class="ads-site">ADS </div>

<p>First Paragraph</p>

<p>Second Paragraph</p>

My Function:

global $post; function my_content_div( $content ) { $content = '<div>My div</div>' . $content; return $content; } add_filter('the_content', 'my_content_div');
3
  • Why not just make it part of the template file?
    – Cedon
    Commented Mar 30, 2017 at 0:27
  • content-gallery.php
    – user112214
    Commented Mar 30, 2017 at 0:43
  • 1
    We ask that questions display some research and implementation effort on the part of the asker. What have you tried so far? Why didn't it work? Please review the "How to Ask" page in our help center for a few tips which might help you to improve this question.
    – bosco
    Commented Mar 30, 2017 at 1:31

2 Answers 2

1

Yogenisia's is right that you should use the_content filter.

If you want to insert something before the first paragraph, locate the first <p> in $content, then insert your div with substr_replace.

add_filter( 'the_content', 'namespace_insert_before_first_paragraph' );

function namespace_insert_before_first_paragraph( $content ) { 
    $my_div = '<div> ... </div>';
    $first_para_pos = strpos( $content, '<p' );
    $new_content = substr_replace( $content, $my_div, $first_para_pos, 0 );

    return $new_content;
}

Keep in mind however that many embeds, such as Twitter's, wrap their content in a <p>...</p>.

1
  • You're welcome! Glad I could help.
    – ricotheque
    Commented Mar 31, 2017 at 5:08
0

You can use the_content filter if that helps:

function my_content_div( $content ) {
    $content = '<div>My div</div>' . $content;
    return $content;
}
add_filter('the_content', 'my_content_div');

You can also add global $post; inside the function to get info on the post and have more control when you show the div.

2
  • The div is on top of the image, I need to add before the first paragraph
    – user112214
    Commented Mar 30, 2017 at 0:48
  • global $post; function my_content_div( $content ) { $content = '<div>My div</div>' . $content; return $content; } add_filter('the_content', 'my_content_div');
    – user112214
    Commented Mar 30, 2017 at 0:48