|
<?php |
|
/** |
|
* custom get related posts by tags if not, by cat if not, from all |
|
* @param int $postid take the global post id by default |
|
* @param int $ppp post per page 6 by default |
|
* @return wp_query object |
|
*/ |
|
function custom_get_related_posts( $postid='', $ppp = 6 ){ |
|
//tags |
|
$exclude_ids = array(); $tag__in = array(); |
|
$exclude_ids[] = $postid = ( !empty($postid) )? $postid: get_the_ID(); |
|
$tags = wp_get_post_tags( $postid ); |
|
if( is_array( $tags ) && count( $tags )>0 ) |
|
foreach ($tags as $key => $value) |
|
$tag__in[] = $value->term_id; |
|
$query = new WP_Query( array ( |
|
'tag__in' => $tag__in, |
|
'posts_per_page' => $ppp, |
|
'post_type' => 'post', |
|
'post__not_in' => $exclude_ids, |
|
) ); |
|
//categorias |
|
if( $query->post_count < $ppp ){ |
|
foreach ($query->posts as $key => $value) |
|
$exclude_ids[] = $value->ID; |
|
$rest = $ppp - $query->post_count; |
|
$category__in = array(); |
|
$cats = get_the_category( $postid ); |
|
if( is_array( $cats ) && count( $cats )>0 ) |
|
foreach ($cats as $key => $value) |
|
$category__in[] = $value->term_id; |
|
$query2 = new WP_Query( array ( |
|
'category__in' => $category__in, |
|
'posts_per_page' => $rest, |
|
'post_type' => 'post', |
|
'post__not_in' => $exclude_ids, |
|
) ); |
|
$querytmp = new WP_Query(); |
|
$querytmp->posts = array_merge( $query->posts, $query2->posts ); |
|
$querytmp->post_count = count( $querytmp->posts ); |
|
$query = $querytmp; |
|
} |
|
//todos los posts |
|
if( $query->post_count < $ppp ){ |
|
foreach ($query->posts as $key => $value) |
|
$exclude_ids[] = $value->ID; |
|
$rest = $ppp - $query->post_count; |
|
$query2 = new WP_Query( array ( |
|
'posts_per_page' => $rest, |
|
'post_type' => 'post', |
|
'post__not_in' => $exclude_ids, |
|
) ); |
|
$querytmp = new WP_Query(); |
|
$querytmp->posts = array_merge( $query->posts, $query2->posts ); |
|
$querytmp->post_count = count( $querytmp->posts ); |
|
$query = $querytmp; |
|
} |
|
return $query; |
|
} |
|
?> |