Wordpress - display 3 related posts regardless of the post type, custom or otherwise -
i'm trying display 3 posts below single post view (i have custom post types set want query work on single post pages regardless of post type).
however code below don't related posts displayed. when removed .
3 related posts display current post being 1 of them. hence why added 'exclude' don't see why not displaying when add in.
'&exclude=' . $current
any appreciate. thanks
<?php $backup = $post; $current = $post->id; //current page id global $post; $thispost = get_post_type(); //current custom post $myposts = get_posts('numberposts=3&order=desc&orderby=id&post_type=' . $thispost . '&exclude=' . $current); $check = count($myposts); if ($check > 1 ) { ?> <h1 id="recent">related</h1> <div id="related" class="group"> <ul class="group"> <?php foreach($myposts $post) : setup_postdata($post); ?> <li> <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"> <article> <h1 class="entry-title"><?php the_title() ?></h1> <div class="name-date"><?php the_time('f j, y'); ?></div> <div class="theexcerpt"><?php the_excerpt(); ?></div> </article> </a> </li> <?php endforeach; ?> </ul> <?php $post = $backup; wp_reset_query(); ?> </div><!-- #related --> <?php } ?>
instead of using get_posts(), use wp_query
<?php // might need use wp_reset_query(); // here if have query before 1 global $post; $current_post_type = get_post_type( $post ); // query arguments $args = array( 'posts_per_page' => 3, 'order' => 'desc', 'orderby' => 'id', 'post_type' => $current_post_type, 'post__not_in' => array( $post->id ) ); // create related query $rel_query = new wp_query( $args ); // check if there related posts if( $rel_query->have_posts() ) : ?> <h1 id="recent">related</h1> <div id="related" class="group"> <ul class="group"> <?php // loop while ( $rel_query->have_posts() ) : $rel_query->the_post(); ?> <li> <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark"> <article> <h1 class="entry-title"><?php the_title() ?></h1> <div class="name-date"><?php the_time('f j, y'); ?></div> <div class="theexcerpt"><?php the_excerpt(); ?></div> </article> </a> </li> <?php endwhile; ?> </ul><!-- .group --> </div><!-- #related --> <?php endif; // reset query wp_reset_query(); ?>
try out code above , modify own need. modified suit own markup.