I need to add a div before the first paragraph.


<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');

closed as unclear what you're asking by Michael, bosco, cjbj, Dave Romsey, Robert hue Apr 12 '17 at 5:18

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • Why not just make it part of the template file? – Cedon Mar 30 '17 at 0:27
  • content-gallery.php – Rikuo Nura Mar 30 '17 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 Mar 30 '17 at 1:31

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>.

  • You're welcome! Glad I could help. – ricotheque Mar 31 '17 at 5:08

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.

  • The div is on top of the image, I need to add before the first paragraph – Rikuo Nura Mar 30 '17 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'); – Rikuo Nura Mar 30 '17 at 0:48

Not the answer you're looking for? Browse other questions tagged or ask your own question.