Gabrielyan
7/24/2017 - 7:08 PM

Список постов с общими категориями

Список постов с общими категориями

<?php

add_filter('the_content', function($content) {
    if(!is_singular()) {
        return $content;
    }
    $terms = get_the_terms(get_the_ID(), 'category');

    $categories = [];

    foreach ($terms as $term)
        $categories[] = $term;

    $loop = new WP_Query([
        'cat__in' => $categories,
        'posts_per_page' => 5,
        'post__not_in' => [get_the_ID()],
        'orderby' => 'rand'
    ]);

    if($loop->have_posts()) {
        $content .= '<ul>';
        while ($loop->have_posts()) {
            $loop->the_post();
            $content .= the_title(
                '<li><a href="' . get_permalink() . '">',
                '</a></li>',
                false
            );
        }
        $content .= '</ul>';
        wp_reset_query();
    }
    return $content;
});