hi!
I am building a blog(kind of) in wordpress and I am using custom post type ui and advanced custom fields.
When I go to a posts single page (single-entry.php) I want to show related posts at the bottom.
I have a taxonomy called “category” and I want to show posts that are under the same categories at the bottom of the page (under the mainpost).
Can anyone help me with this?
Edit:
So i found a script that seems to be working, except I think i need to edit some things (but don’t know how).
// Create a query for the custom taxonomy
function related_posts_by_taxonomy( $post_id, $taxonomy, $args=array() ) {
$query = new WP_Query();
$terms = wp_get_object_terms( $post_id, $taxonomy );
// Make sure we have terms from the current post
if ( count( $terms ) ) {
$post_ids = get_objects_in_term( $terms[0]->term_id, $taxonomy );
$post = get_post( $post_id );
$post_type = get_post_type( $post );
// Only search for the custom taxonomy on whichever post_type
// we AREN'T currently on
// This refers to the custom post_types you created so
// make sure they are spelled/capitalized correctly
if ( strcasecmp($post_type, 'sites') == 0 ) {
$type = 'sites';
} else {
$type = 'sites';
}
$args = wp_parse_args( $args, array(
'post_type' => $type,
'post__in' => $post_ids,
'taxonomy' => $taxonomy,
'term' => $terms[0]->slug,
) );
$query = new WP_Query( $args );
}
// Return our results in query form
return $query;
}
And then this to display:
<?php $related = related_posts_by_taxonomy( $post->ID, 'category' );
while ( $related->have_posts() ): $related->the_post(); ?>
<div class="medium-6 columns end">
<div class="inner">
<a href="<?php echo get_permalink(); ?>" class="img-container">
<div class="img-overlay"></div>
<img src="<?php the_field('thumb'); ?>" />
</a>
<div class="text-container">
<a href="<?php the_field('url'); ?>"><?php the_field('sitename'); ?></a>
</div>
</div>
</div>
<?php endwhile; ?>
The problem I have now is that the current post is also shown as related post (to itself), I want to show related posts by category but I don’t want to show the post i am currently reading.
And also this part:
// Only search for the custom taxonomy on whichever post_type
// we AREN'T currently on
// This refers to the custom post_types you created so
// make sure they are spelled/capitalized correctly
if ( strcasecmp($post_type, 'sites') == 0 ) {
$type = 'video';
} else {
$type = 'sites';
}
I am only using one post-type, so how can a edit this accordingly?
in the while loop you want to skip over when it reaches the post id of that the page is currently on something like this:
related_posts_by_taxonomy( $post->ID, 'category' );
while ( $related->have_posts() ): $related->the_post();
if($post->ID == get_the_ID())
continue; /* this will skip and go onto the next post in the loop */
?>