|
<?php |
|
|
|
/* |
|
* NOTE: This is a portion of a tutorial: |
|
* |
|
* @link https://johnregan3.wordpress.com/how-to-get-wordpress-related-posts |
|
*/ |
|
|
|
// Run the query. |
|
$query = new WP_Query( $args ); |
|
|
|
/* |
|
* NEW STUFF BELOW. |
|
* |
|
* Notice that we'll be repeating some code here. |
|
* We'll clean that up in the next step. |
|
*/ |
|
|
|
// If we have posts, return them. Else, we'll continue on. |
|
if ( ! empty( $query->posts ) && count( $query->posts ) >= $count ) { |
|
return $query->posts; |
|
} |
|
|
|
// Since we're continuing, relabel our results for clarity. |
|
$posts = $query->posts; |
|
|
|
// Update our $args so we don't duplicate any existing posts in the future. |
|
$args['post__not_in'] = wp_list_pluck( $posts, 'ID' ); |
|
|
|
/* |
|
* Remove the search for a specific author. |
|
* |
|
* This action will be repeated soon with the taxonomy args. |
|
* Note that we'll make this code more efficient in the next step. |
|
*/ |
|
unset( $args['author'] ); |
|
|
|
// Run a new query, still searching for posts with the same topics and post type. |
|
$query = new WP_Query( $args ); |
|
|
|
if ( ! empty( $query->posts ) && is_array( $query->posts ) ) { |
|
$new_posts = $query->posts; |
|
|
|
// Merge new posts with existing posts. |
|
$posts = $posts + $new_posts; |
|
} |
|
|
|
// If we now have enough posts, return them. |
|
if ( ! empty( $posts ) && count( $posts ) >= $count ) { |
|
// Make sure the new array of posts doesn't exceed the number of posts we need. |
|
$posts = array_slice( $posts, 0, $count ); |
|
|
|
return $posts; |
|
} |
|
|
|
/* |
|
* Remove the search for specific taxonomy terms, leaving |
|
* only the post type restriction. |
|
* |
|
* Note that we'll make this code more efficient in the next step. |
|
*/ |
|
unset( $args['tax_query'] ); |
|
|
|
$query = new WP_Query( $args ); |
|
|
|
if ( ! empty( $query->posts ) && is_array( $query->posts ) ) { |
|
$new_posts = $query->posts; |
|
$posts = $posts + $new_posts; |
|
} |
|
|
|
// Make sure we don't exceed the number of $count. |
|
return array_slice( $posts, 0, $count ); |