|
<?php |
|
/** |
|
* Build a posts array, used for related posts. |
|
* |
|
* - It grabs a random number of posts up to $limit with the same $taxonomy and same $post_type as $post_id |
|
* And if you haven't hit the limit, then gets random posts. |
|
* |
|
* - To use this, refer to the code to the bottom |
|
* |
|
* @param integer $post_id The integer of the amount posts we have |
|
* @param mixed $taxonomy The taxonomy we're using, or false if not present |
|
* @param mixed $post_type The post type string or array we're using |
|
* @param integer $limit The number of posts to return |
|
* @return array |
|
*/ |
|
function dwinrhys_build_related_posts_array($post_id, $taxonomy = false, $post_type = 'post', $limit = 3) |
|
{ |
|
|
|
$exclude = array($post_id); |
|
$post_ids = array(); |
|
|
|
|
|
if ($taxonomy) { |
|
|
|
$term_obj_list = get_the_terms($post_id, $taxonomy); |
|
|
|
|
|
if (!empty($term_obj_list) && !is_wp_error($term_obj_list)) { |
|
$termnames = wp_list_pluck($term_obj_list, 'name'); |
|
} |
|
|
|
if ($termnames) { |
|
|
|
$firstpass = new WP_Query( |
|
array( |
|
'post_type' => $post_type, |
|
'post__not_in' => $exclude, |
|
'orderby' => 'rand', |
|
'posts_per_page' => $limit, |
|
'tax_query' => array( |
|
array( |
|
'taxonomy' => $taxonomy, |
|
'field' => 'name', |
|
'terms' => $termnames |
|
) |
|
), |
|
) |
|
); |
|
|
|
if ($firstpass->have_posts()) { |
|
while ($firstpass->have_posts()) { |
|
$firstpass->the_post(); |
|
$post_ids[] = get_the_ID(); |
|
$exclude[] = get_the_ID(); |
|
} |
|
} |
|
|
|
wp_reset_postdata(); |
|
} |
|
} |
|
|
|
// If we don't have enough, lets return more general posts |
|
if (count($post_ids) < $limit) { |
|
$secondpass = new WP_Query( |
|
array( |
|
'post_type' => $post_type, |
|
'post__not_in' => $exclude, |
|
'orderby' => 'rand', |
|
'posts_per_page' => $limit |
|
) |
|
); |
|
|
|
if ($secondpass->have_posts()) { |
|
while ($secondpass->have_posts()) { |
|
$secondpass->the_post(); |
|
$post_ids[] = get_the_ID(); |
|
} |
|
} |
|
|
|
wp_reset_postdata(); |
|
} |
|
|
|
$post_ids_to_return = array_slice($post_ids, 0, $limit); |
|
|
|
return $post_ids_to_return; |
|
} |
|
|
|
// Get three of the latest posts from the same category as the current post |
|
$related_posts = dwinrhys_build_related_posts_array( get_the_id(), 'category' ); |
|
// You need to do this |
|
global $post; |
|
|
|
foreach ($related_posts as $post) { |
|
get_post($post); |
|
|
|
// Do the display code here |
|
} |
|
|
|
wp_reset_postdata(); |