|
<?php |
|
/** |
|
* Get category IDs of current post. |
|
*/ |
|
function bt_get_current_post_category_ids($post_id) { |
|
$cat_ids = wp_get_post_categories( $post_id, array('fields' => 'ids') ); |
|
|
|
if (empty($cat_ids) || is_wp_error($cat_ids)) { |
|
return array(); |
|
} |
|
|
|
if (!is_array($cat_ids)) { |
|
$cat_ids = array($cat_ids); |
|
} |
|
|
|
return $cat_ids; |
|
} |
|
|
|
/** |
|
* Get tag IDs of current post. |
|
*/ |
|
function bt_get_current_post_tag_ids($post_id) { |
|
$tag_ids = wp_get_post_tags( $post_id, array('fields' => 'ids') ); |
|
|
|
if (empty($tag_ids) || is_wp_error($tag_ids)) { |
|
return array(); |
|
} |
|
|
|
if (!is_array($tag_ids)) { |
|
$tag_ids = array($cat_ids); |
|
} |
|
|
|
return $tag_ids; |
|
} |
|
|
|
/** |
|
* Query related posts. |
|
*/ |
|
function bt_query_related_posts($post_id, $num = 3) { |
|
$args = array( |
|
'post_type' => 'post', |
|
'post_status' => 'publish', |
|
'showposts' => $num, |
|
'orderby' => 'date', |
|
'order' => 'desc', |
|
'post__not_in' => array($post_id) |
|
); |
|
|
|
$tag_ids = array(); |
|
$cat_ids = array(); |
|
|
|
if (get_post_type($post_id) == 'post') { |
|
$cat_ids = bt_get_current_post_category_ids($post_id); |
|
$tag_ids = bt_get_current_post_tag_ids($post_id); |
|
} |
|
|
|
if (!empty($cat_ids) || !empty($tag_ids)) { |
|
$args['tax_query'] = array( |
|
'relation' => 'OR' |
|
); |
|
|
|
if (!empty($tag_ids)) { |
|
$args['tax_query'][] = array( |
|
'taxonomy' => 'post_tag', |
|
'field' => 'term_id', |
|
'terms' => $tag_ids |
|
); |
|
} |
|
|
|
if (!empty($cat_ids)) { |
|
$args['tax_query'][] = array( |
|
'taxonomy' => 'category', |
|
'field' => 'term_id', |
|
'terms' => $cat_ids, |
|
'include_children' => false |
|
); |
|
} |
|
|
|
return new WP_Query($args); |
|
} |
|
|
|
return false; |
|
} |
|
|
|
/** |
|
* Usage in single.php or template part. |
|
*/ |
|
$related = bt_query_related_posts($post->ID, 3); |
|
if ($related && $related->have_posts()) : |
|
?> |
|
<div> |
|
<h4><?php _e('Related Articles'); ?></h4> |
|
<div class="row"> |
|
<?php while ($related->have_posts()) : $related->the_post(); ?> |
|
<div class="col col-md-8"> |
|
<?php if (has_post_thumbnail()) : ?> |
|
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> |
|
<?php the_post_thumbnail(); ?> |
|
</a> |
|
<?php endif; ?> |
|
<div class="post-meta"> |
|
<span class="post-categories"><?php the_category(', '); ?></span> |
|
<span class="post-date"><?php the_time('F j, Y'); ?></span> |
|
</div> |
|
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> |
|
</div> |
|
<?php endwhile; ?> |
|
</div> |
|
</div> |
|
<?php |
|
wp_reset_postdata(); |
|
endif; |
What is this code meant for? I want to show related post on my blog without using a plugin. I am using Genesis Framework.