如何按类别显示相关帖子

时间:2012-02-05 作者:Felix

在我的图库网站中,我想在当前图片下显示其他图片(单篇文章)。我看到了更多的代码,但我要求指定类别,但我不想在代码中手动指定类别,我想让代码本身获得类别ID或名称。如果我能得到完整的帖子而不是帖子标题,这样我就可以在主页和分类中显示出来,这对我来说会容易得多

3 个回复
最合适的回答,由SO网友:Sufiyan Ghori 整理而成

问题已经提出,答案也已经发布,

How to display related posts from same category?

在单曲中添加此代码。php在循环之后,无论您想在何处显示相关帖子,

<?php

$related = get_posts( array( \'category__in\' => wp_get_post_categories($post->ID), \'numberposts\' => 5, \'post__not_in\' => array($post->ID) ) );
if( $related ) foreach( $related as $post ) {
setup_postdata($post); ?>
 <ul> 
        <li>
        <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a>
            <?php the_content(\'Read the rest of this entry &raquo;\'); ?>
        </li>
    </ul>   
<?php }
wp_reset_postdata(); ?>
它将显示与文章摘录和标题相同类别的相关文章,但是如果希望此代码仅显示相关文章的标题,请删除此行,

<?php the_content(\'Read the rest of this entry &raquo;\'); ?>

SO网友:Lawrence Oputa

下面是另一个干净且非常灵活的选项:

将此代码放入函数中。php文件

function example_cats_related_post() {

    $post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category( $post_id );

    if(!empty($categories) && !is_wp_error($categories)):
        foreach ($categories as $category):
            array_push($cat_ids, $category->term_id);
        endforeach;
    endif;

    $current_post_type = get_post_type($post_id);

    $query_args = array( 
        \'category__in\'   => $cat_ids,
        \'post_type\'      => $current_post_type,
        \'post__not_in\'    => array($post_id),
        \'posts_per_page\'  => \'3\',
     );

    $related_cats_post = new WP_Query( $query_args );

    if($related_cats_post->have_posts()):
         while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
            <ul>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                    <?php the_content(); ?>
                </li>
            </ul>
        <?php endwhile;

        // Restore original Post Data
        wp_reset_postdata();
     endif;

}
现在,您可以使用以下命令在站点中的任意位置调用该函数:

<?php example_cats_related_post() ?>
您可能需要删除列表元素或根据需要设置其样式。

SO网友:Lucas Bustamante

这是开发人员的高级示例。它支持自定义帖子类型和自定义分类法,包括多个分类法的匹配。

// $post pointing to a WP_Post instance of the current post.

$query = new WP_Query(
    [
        \'post_type\'      => $relatedPostType,
        \'posts_per_page\' => 6,
        \'tax_query\'      => buildTaxonomyForRelatedPosts($post),
        \'post__not_in\'   => [$post->ID],
    ]
);

// The array of related posts
$relatedPosts = $query->get_posts();

function buildTaxonomyForRelatedPosts(WP_Post $post) {
    switch ($post->post_type) {
        case \'post\':
            $taxonomies = [\'category\', \'post_tag\'];
            break;
        case \'news\':
            $taxonomies = [\'newscategory\', \'newstags\'];
            break;
        default:
            return [];
    }

    $taxQuery = [
        \'relation\' => \'OR\',
    ];

    foreach ($taxonomies as $taxonomy) {
        $taxQuery[] = [
            \'taxonomy\' => $taxonomy,
            \'field\'    => \'slug\',
            \'terms\'    => array_filter(wp_get_object_terms($post->ID, $taxonomy, [\'fields\' => \'slugs\']), function($termSlug) {
                return strtolower($termSlug) !== \'uncategorized\';
            }),
        ];
    }

    return $taxQuery;
}

功能buildTaxonomyForRelatedPosts 基本上使用以下结构构建阵列:

\'tax_query\' => [
    \'relation\' => \'OR\',
    [
        \'taxonomy\' => \'movie_genre\',
        \'field\'    => \'slug\',
        \'terms\'    => [\'action\', \'comedy\', \'drama\'],
    ],
    [
        \'taxonomy\' => \'actor\',
        \'field\'    => \'slug\',
        \'terms\'    => [\'foo\', \'bar\', \'baz\'],
    ],
];

https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters

结束