3

Ранее для добавления рекламного кода после определенного по счету </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;
}

Теперь надо добавить код после закрывающего </div> определенного класса В каждой записи есть блок поделиться от яндекса, он обернут в <div class="ya-share2"> вот после этого закрывающего </div> и требуется добавить код.

2
  • что мешает просто добавить этот код в том шаблоне, в котором вы выводите блок яндекса?
    – alenkins
    6 июн 2016 в 16:00
  • Дело в том что кнопки поделиться были добавлены вручную в каждую статью отдельно (т.е. находятся в "теле" статьи)
    – c3589668
    6 июн 2016 в 16:15

1 ответ 1

1

Если на странице один ya-share2 и между <div class="ya-share2"> и нужным </div> нет других </div>, то должно помочь:

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;
}
1
  • Большое спасибо. Помогло.
    – c3589668
    7 июн 2016 в 10:06

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.