Related Posts with SearchWP

/** * Related Posts * */ function ea_related_posts() { $related_to_show = 6; $related = ea_get_related_posts( $related_to_show ); // Display Related Posts $loop = new WP_Query( array( 'post__in' => $related, 'orderby' => 'post__in', 'posts_per_page' => $related_to_show, ) ); if( $loop->have_posts() ): echo '<section class="related-posts">'; echo '<header><h3>Related Posts</h3></header>'; while( $loop->have_posts() ): $loop->the_post(); get_template_part( 'partials/archive', 'related' ); endwhile; echo '</section>'; endif; wp_reset_postdata(); } add_action( 'genesis_after_entry', 'ea_related_posts' ); /** * Get Related Posts * */ function ea_get_related_posts( $related_to_show = false ) { $related_to_show = !empty( $related_to_show ) ? intval( $related_to_show ) : get_option( 'posts_per_page' ); // Use SearchWP if( class_exists( 'SearchWP_Related' ) ) { // Instantiate SearchWP Related $searchwp_related = new SearchWP_Related(); // Use the keywords as defined in the SearchWP Related meta box $keywords = get_post_meta( get_the_ID(), $searchwp_related->meta_key, true ); if( empty( $keywords ) ) $keywords = get_the_title(); $args = array( 's' => $keywords, // The stored keywords to use 'engine' => 'default', // the SearchWP engine to use 'posts_per_page' => $related_to_show, 'post__not_in' => array( get_the_ID() ), ); // Retrieve Related content for the current post $related = $searchwp_related->get( $args ); // Fallback, use primary category } else { $loop = new WP_Query( array( 'posts_per_page' => $related_to_show, 'category_name' => ea_first_term( 'category', 'slug' ), 'post__not_in' => array( get_the_ID() ), 'fields' => 'ids', )); if( ! is_wp_error( $loop ) && !empty( $loop->posts ) ) $related = $loop->posts; } return $related; }

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk