php – How to add code to content after a specific one on a wordpress site<div> ?

Question:

Previously, I used the following code to add an ad code after a certain account </h2>

add_filter('the_content', 'wpse_ad_content');

function wpse_ad_content($content)
{
    if (!is_single()) return $content;
    $paragraphAfter = 2; //Enter number of paragraphs to display ad after.
    $content = explode("</h2>", $content);
    $new_content = '';
    for ($i = 0; $i < count($content); $i++) {
        if ($i == $paragraphAfter) {
            $new_content.= '<div style="margin-bottom: 10px;">';
            $new_content.= 'Рекламный блок';
            $new_content.= '</div>';
        }

        $new_content.= $content[$i] . "</h2>";
    }

    return $new_content;
}

Now you need to add the code after the closing </div> certain class. Each post has a share block from Yandex, it is wrapped in <div class="ya-share2"> after this closing </div> and you need to add the code.

Answer:

If on page one ya-share2 between <div class="ya-share2"> "> and fit </div> otherwise </div> , it should help:

add_filter('the_content', 'wpse_ad_content');

function wpse_ad_content($content)
{
    if (!is_single()) return $content;

    $new_content = '<div style="margin-bottom: 10px;">';           
    $new_content.= 'Рекламный блок';
    $new_content.= '</div>';

    $content = explode("ya-share2", $content, 2);
    $add_content = explode("</div>", $content[1], 2);
    $add_content[1] =  $new_content.$add_content[1];
    $new_content = $content[0] . "ya-share2" . $add_content[0]."</div>" . $add_content[1];

    return $new_content;
}
Scroll to Top