-
-
Save billerickson/1ef3cb9869c06512723c5f6588e0d102 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Get Related Posts | |
* @see https://www.billerickson.net/related-posts-with-searchwp/ | |
* | |
*/ | |
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' ); | |
$related = array(); | |
// Use SearchWP | |
if( class_exists( 'SearchWP_Related' ) && count( $related ) < $related_to_show ) { | |
// 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 - count( $related ), | |
'post__not_in' => array( get_the_ID() ), | |
'fields' => 'ids', | |
); | |
// Retrieve Related content for the current post | |
$swp_related = $searchwp_related->get( $args ); | |
if( !empty( $swp_related ) ) { | |
$related = array_merge( $related, $swp_related ); | |
} | |
} | |
// Fallback, use primary category | |
if( count( $related ) < $related_to_show ) { | |
$loop = new WP_Query( array( | |
'posts_per_page' => $related_to_show - count( $related ), | |
'category_name' => ea_first_term( 'category', 'slug' ), | |
'post__not_in' => array_merge( $related, array( get_the_ID() ) ), | |
'fields' => 'ids', | |
)); | |
if( ! is_wp_error( $loop ) && !empty( $loop->posts ) ) | |
$related = array_merge( $related, $loop->posts ); | |
} | |
return $related; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment