wp rlated post query

Solutions on MaxInterview for wp rlated post query by the best coders in the world

showing results for - "wp rlated post query"
Simon
18 Nov 2018
1function example_cats_related_post() {
2
3    $post_id = get_the_ID();
4    $cat_ids = array();
5    $categories = get_the_category( $post_id );
6
7    if(!empty($categories) && !is_wp_error($categories)):
8        foreach ($categories as $category):
9            array_push($cat_ids, $category->term_id);
10        endforeach;
11    endif;
12
13    $current_post_type = get_post_type($post_id);
14
15    $query_args = array( 
16        'category__in'   => $cat_ids,
17        'post_type'      => $current_post_type,
18        'post__not_in'    => array($post_id),
19        'posts_per_page'  => '3',
20     );
21
22    $related_cats_post = new WP_Query( $query_args );
23
24    if($related_cats_post->have_posts()):
25         while($related_cats_post->have_posts()): $related_cats_post->the_post(); ?>
26            <ul>
27                <li>
28                    <a href="<?php the_permalink(); ?>">
29                        <?php the_title(); ?>
30                    </a>
31                    <?php the_content(); ?>
32                </li>
33            </ul>
34        <?php endwhile;
35
36        // Restore original Post Data
37        wp_reset_postdata();
38     endif;
39
40}
41
similar questions
queries leading to this page
wp rlated post query