Как вставить код в конкретное место страницы Вордпресса?

Ссылка скопирована
1 ответ

Добры день.
Есть страница single.php. Она состоит из хедера, контента, популярных записей и футера.
Подскажите, пожалуйста, как вставить код между контентом и популярными записями через function.php ?

Дополнительные вопросы

Ответы:

Нужно смотреть код конкретной темы, но общий принцип такой: в дочерней теме вы либо вешаете событие на нужный вам хук, либо заменяете весь шаблон single.php

  • Именно. В данном случае, я не могу прописать хук. Он есть, но я не понимаю как указать, нужное мне место (между контентом и популярными записями).
    если писать как add_action('the_content', 'my_function'); то нужно писать код, который бы вы водил содержимое поста заново, я не знаю, насколько это корректно.

    а через add_action('wp_footer', 'my_function'); вывод кода происходи перед футера и после популярных записей. Я никак не могу найти, как может называться место перед related_posts

  • silatal, а как related_posts выводятся?
  • Артем Золин, Выводится через отдельный файл related-posts.php
    <?php  /**  * ****************************************************************************  *  *   НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ  *   DON'T EDIT THIS FILE  *  *   После обновления Вы потереяете все изменения. Используйте дочернюю тему  *   After update you will lose all changes. Use child theme  *  *   https://docs.wpshop.ru/start/child-themes  *  * *****************************************************************************  *  * @package reboot  */  global $wpshop_core; global $class_advertising;  if (is_page()) {     $related_count_mod = $wpshop_core->get_option('structure_page_related'); } else {     $related_count_mod = $wpshop_core->get_option('structure_single_related'); } $related_yarpp_enabled = apply_filters(THEME_SLUG . '_yarpp_enabled', false);   if (!empty($related_count_mod) && !$related_yarpp_enabled) {     $post__not_in = [];     $related_articles = [];     $related_posts_category_id_exclude = [];      $related_post_taxonomy_order    = $wpshop_core->get_option('related_post_taxonomy_order');     $related_posts_exclude          = $wpshop_core->get_option('related_posts_exclude');     $related_posts_category_exclude = $wpshop_core->get_option('related_posts_category_exclude');      if (!empty($related_posts_exclude)) {         $related_posts_exclude = explode(',', $related_posts_exclude);          foreach ($related_posts_exclude as $key => $value) {             $post__not_in[] = $related_posts_exclude[$key];         }     }      if (!empty($related_posts_category_exclude)) {         $related_posts_category_exclude = explode(',', $related_posts_category_exclude);          foreach ($related_posts_category_exclude as $key => $value) {             $related_posts_category_id_exclude[$key] = '-' . $related_posts_category_exclude[$key];         }     }      $related_count = 8;     if (is_numeric($related_count_mod) && $related_count_mod > -1) {         if ($related_count_mod > 50) $related_count_mod = 50;         $related_count = $related_count_mod;     }      if (is_single()) {         $related_posts_ids = get_post_meta($post->ID, 'related_posts_ids', true);          // если указаны посты - набираем их         if (!empty($related_posts_ids)) {             $related_posts_id_exp = explode(',', $related_posts_ids);              if (is_array($related_posts_id_exp)) {                 $related_posts_ids = array_map('trim', $related_posts_id_exp);             } else {                 $related_posts_ids = [$related_posts_ids];             }              if (!empty($related_posts_exclude)) {                 $related_posts_ids = array_diff($related_posts_ids, $related_posts_exclude);             }              if (!empty($related_posts_ids)) {                 $related_articles = get_posts([                     'posts_per_page' => $related_count,                     'post__in'       => $related_posts_ids,                     'post__not_in'   => [$post->ID],                 ]);             }         }          // если не хватило, добираем из категории         if (count($related_articles) < $related_count) {             // сколько осталось постов             $delta = $related_count - count($related_articles);              // убираем текущий пост + уже выведенные             $post__not_in[] = $post->ID;             foreach ($related_articles as $article) {                 $post__not_in[] = $article->ID;             }              if ($related_post_taxonomy_order == 'categories') {                 // подготавливаем категории                 global $post;                 $category_ids = [];                 $categories = get_the_category($post->ID);                 if ($categories) {                     foreach ($categories as $_category) {                         if (!empty($related_posts_category_exclude)) {                             if (!in_array($_category->term_id, $related_posts_category_exclude)) $category_ids[] = $_category->term_id;                         } else {                             $category_ids[] = $_category->term_id;                         }                     }                 }                  if (!empty($category_ids)) {                     $related_articles_taxonomy = get_posts(                         apply_filters(THEME_SLUG . '_related_get_posts_category_args', [                             'posts_per_page' => $delta,                             'category__in'   => $category_ids,                             'post__not_in'   => $post__not_in,                         ])                     );                 }             } else {                 // подготавливаем метки                 global $post;                 $tag_ids = [];                 $tags = get_the_tags($post->ID);                 if ($tags) {                     foreach ($tags as $tag) {                         $tag_ids[] = $tag->term_taxonomy_id;                     }                 }                  $related_articles_taxonomy = get_posts(                     apply_filters(THEME_SLUG . '_related_get_posts_category_args', [                         'posts_per_page' => $delta,                         'category'       => $related_posts_category_id_exclude,                         'tag__in'        => $tag_ids,                         'post__not_in'   => $post__not_in,                     ])                 );             }              if (!empty($related_articles_taxonomy)) $related_articles = array_merge($related_articles, $related_articles_taxonomy);              // если не хватило, добираем рандом             if (count($related_articles) < $related_count) {                 // сколько осталось постов                 $delta = $related_count - count($related_articles);                  // убираем текущий пост + уже выведенные                 $post__not_in[] = $post->ID;                 foreach ($related_articles as $article) {                     $post__not_in[] = $article->ID;                 }                  $related_articles_second = get_posts(                     apply_filters(THEME_SLUG . '_related_get_posts_rand_args', [                         'posts_per_page' => $delta,                         'category'       => $related_posts_category_id_exclude,                         'orderby'        => 'rand',                         'post__not_in'   => $post__not_in,                     ])                 );                  // если все ок, объединяем                 if (!empty($related_articles_second)) $related_articles = array_merge($related_articles, $related_articles_second);             }         }     } else {         if (!empty($post->ID)) {             $related_posts_ids = get_post_meta($post->ID, 'related_posts_ids', true);         }          // если указаны посты - набираем их         if (!empty($related_posts_ids)) {             $related_posts_id_exp = explode(',', $related_posts_ids);              if (is_array($related_posts_id_exp)) {                 $related_posts_ids = array_map('trim', $related_posts_id_exp);             } else {                 $related_posts_ids = [$related_posts_ids];             }              if (!empty($related_posts_exclude)) {                 $related_posts_ids = array_diff($related_posts_ids, $related_posts_exclude);             }              if (!empty($related_posts_ids)) {                 $related_articles = get_posts([                     'posts_per_page' => $related_count,                     'post__in'       => $related_posts_ids,                     'post__not_in'   => $post__not_in,                 ]);             }         }          // если не хватило, добираем рандом         if (count($related_articles) < $related_count) {             // сколько осталось постов             $delta = $related_count - count($related_articles);              // убираем уже выведенные             foreach ($related_articles as $article) {                 $post__not_in[] = $article->ID;             }              $related_articles_second = get_posts(                 apply_filters(THEME_SLUG . '_related_get_posts_rand_args', [                     'posts_per_page' => $delta,                     'category'       => $related_posts_category_id_exclude,                     'orderby'        => 'rand',                     'post__not_in'   => $post__not_in,                 ])             );              // если все ок, объединяем             if (!empty($related_articles_second)) $related_articles = array_merge($related_articles, $related_articles_second);         }     }      if (!empty($related_articles)) {         echo '<div id="related-posts" class="related-posts fixed">';          do_action(THEME_SLUG . '_before_related');          echo '<div class="related-posts__header">' . apply_filters(THEME_SLUG . '_related_title', __('You may also like', THEME_TEXTDOMAIN)) . '</div>';          echo $class_advertising->show_ad('before_related');          echo '<div class="post-cards post-cards--vertical">';         $n = 0;         foreach ($related_articles as $post) {             setup_postdata($post);             $n++;             get_template_part('template-parts/post-card/related');             do_action(THEME_SLUG . '_after_post_card', $n, 'related');         }         wp_reset_postdata();         echo '</div>';          echo $class_advertising->show_ad('after_related');          do_action(THEME_SLUG . '_after_related');          echo '</div>';     } } else {     /**      * If yarpp enabled      */     if (function_exists('yarpp_related') && $related_yarpp_enabled) {         yarpp_related();     } }

    <?php /** * **************************************************************************** * * НЕ РЕДАКТИРУЙТЕ ЭТОТ ФАЙЛ * DON'T EDIT THIS FILE * * После обновления Вы потереяете все изменения. Используйте дочернюю тему * After update you will lose all changes. Use child theme * * https://docs.wpshop.ru/start/child-themes * * ***************************************************************************** * * @package reboot */ global $wpshop_core; global $class_advertising; if (is_page()) { $related_count_mod = $wpshop_core->get_option('structure_page_related'); } else { $related_count_mod = $wpshop_core->get_option('structure_single_related'); } $related_yarpp_enabled = apply_filters(THEME_SLUG . '_yarpp_enabled', false); if (!empty($related_count_mod) && !$related_yarpp_enabled) { $post__not_in = []; $related_articles = []; $related_posts_category_id_exclude = []; $related_post_taxonomy_order = $wpshop_core->get_option('related_post_taxonomy_order'); $related_posts_exclude = $wpshop_core->get_option('related_posts_exclude'); $related_posts_category_exclude = $wpshop_core->get_option('related_posts_category_exclude'); if (!empty($related_posts_exclude)) { $related_posts_exclude = explode(',', $related_posts_exclude); foreach ($related_posts_exclude as $key => $value) { $post__not_in[] = $related_posts_exclude[$key]; } } if (!empty($related_posts_category_exclude)) { $related_posts_category_exclude = explode(',', $related_posts_category_exclude); foreach ($related_posts_category_exclude as $key => $value) { $related_posts_category_id_exclude[$key] = '-' . $related_posts_category_exclude[$key]; } } $related_count = 8; if (is_numeric($related_count_mod) && $related_count_mod > -1) { if ($related_count_mod > 50) $related_count_mod = 50; $related_count = $related_count_mod; } if (is_single()) { $related_posts_ids = get_post_meta($post->ID, 'related_posts_ids', true); // если указаны посты - набираем их if (!empty($related_posts_ids)) { $related_posts_id_exp = explode(',', $related_posts_ids); if (is_array($related_posts_id_exp)) { $related_posts_ids = array_map('trim', $related_posts_id_exp); } else { $related_posts_ids = [$related_posts_ids]; } if (!empty($related_posts_exclude)) { $related_posts_ids = array_diff($related_posts_ids, $related_posts_exclude); } if (!empty($related_posts_ids)) { $related_articles = get_posts([ 'posts_per_page' => $related_count, 'post__in' => $related_posts_ids, 'post__not_in' => [$post->ID], ]); } } // если не хватило, добираем из категории if (count($related_articles) < $related_count) { // сколько осталось постов $delta = $related_count - count($related_articles); // убираем текущий пост + уже выведенные $post__not_in[] = $post->ID; foreach ($related_articles as $article) { $post__not_in[] = $article->ID; } if ($related_post_taxonomy_order == 'categories') { // подготавливаем категории global $post; $category_ids = []; $categories = get_the_category($post->ID); if ($categories) { foreach ($categories as $_category) { if (!empty($related_posts_category_exclude)) { if (!in_array($_category->term_id, $related_posts_category_exclude)) $category_ids[] = $_category->term_id; } else { $category_ids[] = $_category->term_id; } } } if (!empty($category_ids)) { $related_articles_taxonomy = get_posts( apply_filters(THEME_SLUG . '_related_get_posts_category_args', [ 'posts_per_page' => $delta, 'category__in' => $category_ids, 'post__not_in' => $post__not_in, ]) ); } } else { // подготавливаем метки global $post; $tag_ids = []; $tags = get_the_tags($post->ID); if ($tags) { foreach ($tags as $tag) { $tag_ids[] = $tag->term_taxonomy_id; } } $related_articles_taxonomy = get_posts( apply_filters(THEME_SLUG . '_related_get_posts_category_args', [ 'posts_per_page' => $delta, 'category' => $related_posts_category_id_exclude, 'tag__in' => $tag_ids, 'post__not_in' => $post__not_in, ]) ); } if (!empty($related_articles_taxonomy)) $related_articles = array_merge($related_articles, $related_articles_taxonomy); // если не хватило, добираем рандом if (count($related_articles) < $related_count) { // сколько осталось постов $delta = $related_count - count($related_articles); // убираем текущий пост + уже выведенные $post__not_in[] = $post->ID; foreach ($related_articles as $article) { $post__not_in[] = $article->ID; } $related_articles_second = get_posts( apply_filters(THEME_SLUG . '_related_get_posts_rand_args', [ 'posts_per_page' => $delta, 'category' => $related_posts_category_id_exclude, 'orderby' => 'rand', 'post__not_in' => $post__not_in, ]) ); // если все ок, объединяем if (!empty($related_articles_second)) $related_articles = array_merge($related_articles, $related_articles_second); } } } else { if (!empty($post->ID)) { $related_posts_ids = get_post_meta($post->ID, 'related_posts_ids', true); } // если указаны посты - набираем их if (!empty($related_posts_ids)) { $related_posts_id_exp = explode(',', $related_posts_ids); if (is_array($related_posts_id_exp)) { $related_posts_ids = array_map('trim', $related_posts_id_exp); } else { $related_posts_ids = [$related_posts_ids]; } if (!empty($related_posts_exclude)) { $related_posts_ids = array_diff($related_posts_ids, $related_posts_exclude); } if (!empty($related_posts_ids)) { $related_articles = get_posts([ 'posts_per_page' => $related_count, 'post__in' => $related_posts_ids, 'post__not_in' => $post__not_in, ]); } } // если не хватило, добираем рандом if (count($related_articles) < $related_count) { // сколько осталось постов $delta = $related_count - count($related_articles); // убираем уже выведенные foreach ($related_articles as $article) { $post__not_in[] = $article->ID; } $related_articles_second = get_posts( apply_filters(THEME_SLUG . '_related_get_posts_rand_args', [ 'posts_per_page' => $delta, 'category' => $related_posts_category_id_exclude, 'orderby' => 'rand', 'post__not_in' => $post__not_in, ]) ); // если все ок, объединяем if (!empty($related_articles_second)) $related_articles = array_merge($related_articles, $related_articles_second); } } if (!empty($related_articles)) { echo '<div id="related-posts" class="related-posts fixed">'; do_action(THEME_SLUG . '_before_related'); echo '<div class="related-posts__header">' . apply_filters(THEME_SLUG . '_related_title', __('You may also like', THEME_TEXTDOMAIN)) . '</div>'; echo $class_advertising->show_ad('before_related'); echo '<div class="post-cards post-cards--vertical">'; $n = 0; foreach ($related_articles as $post) { setup_postdata($post); $n++; get_template_part('template-parts/post-card/related'); do_action(THEME_SLUG . '_after_post_card', $n, 'related'); } wp_reset_postdata(); echo '</div>'; echo $class_advertising->show_ad('after_related'); do_action(THEME_SLUG . '_after_related'); echo '</div>'; } } else { /** * If yarpp enabled */ if (function_exists('yarpp_related') && $related_yarpp_enabled) { yarpp_related(); } }

  • silatal, у меня нет этой темы, покажите где применяется этот файл?
  • Артем Золин, Непонятно где этот файл вызывается, поиск по коду файлов ничего не даёт.
    А вородпресса нет никакой структуры по хукам, как в том же woocommerce. Вопрос то по сути пустяковый, но уже второй день отнимает моё время, а я сегодня отнимаю время у вас.

    Что-то такое:

    Как вставить код в конкретное место страницы Вордпресса?

Как вставить код в конкретное место страницы Вордпресса?

Вова Дружаев @OtshelnikFm Куратор тега WordPress Обо мне расскажет yawncato.com Используйте фильтр the_content wp-kama.ru/hook/the_content#example_35584 pantsarny @pantsarny В вашей теме есть экшен - do_action(THEME_SLUG . '_before_related');
Он не подходит ?

Нужно решить такую задачу?

Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.

Заказать помощь
Лучший ответ
1
Анна SEO Ответ

Если нужно вставить блок между контентом и популярными записями в single.php, самый чистый вариант зависит от темы. Через functions.php это можно сделать только если в нужном месте шаблона есть hook. Если hook нет, фильтр the_content вставит код сразу после контента, но до блока популярных записей только в том случае, если популярные записи выводятся уже после the_content().

Первый вариант — через the_content:

add_filter('the_content', function ($content) {
    if (! is_singular('post') || ! in_the_loop() || ! is_main_query()) {
        return $content;
    }
 
    $block = '<div class="my-after-content-block">Мой блок после контента</div>';
 
    return $content . $block;
});

add_filter('the_content', function ($content) { if (! is_singular('post') || ! in_the_loop() || ! is_main_query()) { return $content; } $block = '<div class="my-after-content-block">Мой блок после контента</div>'; return $content . $block; });

Это подойдёт, если популярные записи идут в шаблоне после вывода контента. Но если тема формирует контент сложнее или популярные записи встроены внутрь того же фильтра, порядок может быть не таким.

Второй вариант — сделать hook в дочерней теме. В шаблоне:

the_content();
do_action('my_after_single_content');
get_template_part('template-parts/popular-posts');

the_content(); do_action('my_after_single_content'); get_template_part('template-parts/popular-posts');

А в functions.php:

add_action('my_after_single_content', function () {
    echo '<div class="my-after-content-block">Мой блок после контента</div>';
});

add_action('my_after_single_content', function () { echo '<div class="my-after-content-block">Мой блок после контента</div>'; });

Это самый управляемый вариант, но он требует правки шаблона дочерней темы.

Третий вариант — shortcode, если блок нужен не на всех страницах, а только там, где вы сами его поставите:

add_shortcode('after_text_block', function () {
    return '<div class="my-after-content-block">Текст или HTML блока</div>';
});

add_shortcode('after_text_block', function () { return '<div class="my-after-content-block">Текст или HTML блока</div>'; });

Не правьте core WordPress и не вставляйте код прямо в родительскую тему, если тема обновляется. Для постоянной доработки лучше дочерняя тема или небольшой site-specific plugin.

Другие ответы (0)

Пока нет других ответов. Будьте первым, кто поможет автору.

Ответить на вопрос

комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Вам также может быть интересно