Создадим плагин одним файлом с автоматической вставкой после статей.
Файл: wp-content/plugins/auto-related-posts/auto-related-posts.php
<?php
/**
* Plugin Name: Auto Related Posts
* Description: Автоматически добавляет похожие записи после контента. Вывод в 2 ряда по 3 статьи.
* Version: 1.0
* Author: Ведерников Сергей
*/
// Запрет прямого доступа
if (!defined('ABSPATH')) {
exit;
}
class AutoRelatedPostsPlugin {
public function __construct() {
add_filter('the_content', array($this, 'auto_insert_related_posts'));
add_action('wp_enqueue_scripts', array($this, 'enqueue_styles'));
add_shortcode('related_posts_grid', array($this, 'related_posts_shortcode'));
}
public function enqueue_styles() {
if (is_single()) {
$css = "
.related-posts-grid-wrapper {
margin: 40px 0;
padding: 30px 0;
border-top: 2px solid #f0f0f0;
border-bottom: 2px solid #f0f0f0;
}
.related-posts-title {
text-align: center;
margin-bottom: 35px;
font-size: 28px;
color: #2c3e50;
font-weight: 600;
}
.related-posts-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 30px;
}
.related-post-item {
background: #ffffff;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
border: 1px solid #eaeaea;
}
.related-post-item:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.related-post-link {
text-decoration: none;
color: inherit;
display: block;
height: 100%;
}
.related-post-thumbnail {
width: 100%;
height: 200px;
overflow: hidden;
position: relative;
}
.related-post-thumbnail img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.related-post-item:hover .related-post-thumbnail img {
transform: scale(1.05);
}
.related-post-content {
padding: 20px;
}
.related-post-heading {
margin: 0 0 12px 0;
font-size: 18px;
line-height: 1.4;
color: #2c3e50;
font-weight: 600;
}
.related-post-excerpt {
font-size: 14px;
line-height: 1.5;
color: #666;
margin: 0;
}
/* Адаптивность */
@media (max-width: 1024px) {
.related-posts-grid {
gap: 20px;
}
.related-post-thumbnail {
height: 180px;
}
}
@media (max-width: 768px) {
.related-posts-grid {
grid-template-columns: 1fr;
gap: 20px;
}
.related-post-thumbnail {
height: 160px;
}
.related-post-content {
padding: 15px;
}
.related-posts-title {
font-size: 24px;
margin-bottom: 25px;
}
}
@media (max-width: 480px) {
.related-posts-title {
font-size: 22px;
}
.related-post-heading {
font-size: 16px;
}
.related-post-excerpt {
font-size: 13px;
}
}
";
wp_add_inline_style('wp-block-library', $css);
}
}
public function auto_insert_related_posts($content) {
// Добавляем только к одиночным записям и не в админке
if (is_single() && !is_admin()) {
$related_posts = $this->get_related_posts_content();
$content .= $related_posts;
}
return $content;
}
public function related_posts_shortcode($atts) {
return $this->get_related_posts_content($atts);
}
private function get_related_posts_content($atts = array()) {
$atts = shortcode_atts(array(
'posts_count' => '6',
'title' => 'Похожие статьи'
), $atts);
ob_start();
global $post;
if (!$post) {
return '';
}
$post_id = $post->ID;
$categories = get_the_category($post_id);
if (!$categories) {
return '<p>Похожих записей не найдено.</p>';
}
$category_ids = array();
foreach($categories as $individual_category) {
$category_ids[] = $individual_category->term_id;
}
$args = array(
'category__in' => $category_ids,
'post__not_in' => array($post_id),
'posts_per_page' => intval($atts['posts_count']),
'ignore_sticky_posts' => 1,
'orderby' => 'rand',
'post_status' => 'publish'
);
$related_query = new WP_Query($args);
if($related_query->have_posts()) {
?>
<div class="related-posts-grid-wrapper">
<h3 class="related-posts-title"><?php echo esc_html($atts['title']); ?></h3>
<div class="related-posts-grid">
<?php while($related_query->have_posts()) : $related_query->the_post(); ?>
<?php
$thumbnail_url = get_the_post_thumbnail_url(get_the_ID(), 'medium');
$excerpt = has_excerpt() ? get_the_excerpt() : wp_trim_words(get_the_content(), 12, '...');
?>
<article class="related-post-item">
<a href="<?php the_permalink(); ?>" class="related-post-link">
<?php if($thumbnail_url) : ?>
<div class="related-post-thumbnail">
<img src="<?php echo esc_url($thumbnail_url); ?>" alt="<?php the_title_attribute(); ?>" />
</div>
<?php endif; ?>
<div class="related-post-content">
<h4 class="related-post-heading"><?php the_title(); ?></h4>
<div class="related-post-excerpt">
<?php echo esc_html($excerpt); ?>
</div>
</div>
</a>
</article>
<?php endwhile; ?>
</div>
</div>
<?php
} else {
echo '<p>Похожих записей не найдено.</p>';
}
wp_reset_postdata();
return ob_get_clean();
}
}
new AutoRelatedPostsPlugin();
// Активация плагина - создаем опции по умолчанию
register_activation_hook(__FILE__, function() {
add_option('auto_related_posts_enabled', 'yes');
});
// Деактивация плагина - чистим настройки
register_deactivation_hook(__FILE__, function() {
delete_option('auto_related_posts_enabled');
});
?>
Установка:
Создайте папку: wp-content/plugins/auto-related-posts/
Поместите в нее файл: auto-related-posts.php
Активируйте плагин в админке WordPress
Что делает плагин:
✅ Автоматически добавляет блок похожих записей после каждой статьи
✅ Вывод в 2 ряда по 3 статьи (всего 6)
✅ Без надписи «скачать изображение» — используется прямое URL изображения
✅ Один файл — все в одном PHP файле (стили включены внутрь)
✅ Адаптивный дизайн — корректно отображается на мобильных
✅ Дополнительно есть шорткод [[related_posts_grid]] для ручного размещения
После активации плагина:
Автоматически после каждой статьи появится блок «Похожие статьи»
Не нужно редактировать файлы темы
Не нужно вставлять шорткоды вручную
Если хотите отключить автоматическую вставку и использовать только шорткод, удалите эту строку из плагина:
php
add_filter(‘the_content’, array($this, ‘auto_insert_related_posts’));
Плагин готов к использованию! Просто активируйте его и похожие записи будут автоматически появляться после ваших статей.
И для использования шорткода в контенте:
html
[[related_posts_grid]]
или с параметрами:
html
[[related_posts_grid posts_count="6" title="Рекомендуемые статьи"]]
Добавить комментарий