admin管理员组

文章数量:1125484

In my gallery site i want to show other pictures under the current picture (in single post). I seen more codes but it i asks to specify the category, but i dont want want specify the category manually in the code I want the code itself to get the category ID or name.It would be much easier for me if i get full posts instead of post title so that I can display it as in home and category

In my gallery site i want to show other pictures under the current picture (in single post). I seen more codes but it i asks to specify the category, but i dont want want specify the category manually in the code I want the code itself to get the category ID or name.It would be much easier for me if i get full posts instead of post title so that I can display it as in home and category

Share Improve this question edited Feb 2, 2024 at 20:06 Jesse Nickles 7357 silver badges19 bronze badges asked Feb 5, 2012 at 16:22 FelixFelix 3332 gold badges5 silver badges11 bronze badges 2
  • possible duplicate of How to display related posts from same category? – kaiser Commented Feb 5, 2012 at 17:21
  • Does this answer your question? How to display related posts from the same category? – Jesse Nickles Commented Feb 3, 2024 at 5:19
Add a comment  | 

3 Answers 3

Reset to default 34

The question has already been asked and the answer has been posted too,

How to display related posts from same category?

Add this code inside your single.php after a loop wherever you want to show related post,

<?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(); ?>

It will display related post from the same category with the post excerpt and title , however if want this code to display just the title of related post then remove this line,

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

Here is another clean and very flexible option:

Put this code in your functions.php file

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;

}

Now you can simply call the function anywhere in your site using:

<?php example_cats_related_post() ?>

You may want to remove the list elements or style them as per your need.

This is an advanced example for developers. It supports custom post types and custom taxonomies, including matches by multiple taxonomies.

// $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;
}

The function buildTaxonomyForRelatedPosts essentially builds an array with this structure:

'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

本文标签: categoriesHow to show related posts by detecting the current category