I am trying to build a villa rentals website. To achieve that, I have created two custom post types. The one is named "villa" and is used to show the villas for rent, and the other one is named "destinations" and is used to show the places where this villas are.
I used the CPT-onomies plugin to make the "destinations" custom post type, a custom taxonomy for my custom post type "villa". There are two custom post types and the one is used as a taxonomy for the other one, to show where is that villa. On each single-villa.php page I want to show one related villa in the end of the post (after the loop), I want that related villa to be related only by destination (which is a custom taxonomy).
I found this article, I followed the instructions and it somehow did the trick for me, unfortunately I cannot figure out two things: 1. First I dont know how to make it show only one related villa (post) instead of all the related posts. 2. I dont know how to to exclude the current post from related posts (there are instructions on how to achieve that on the article I have linked to above but it doen't work for me.)
I added this code to functions.php
// 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 this code to single-villa.php
<?php $related = related_posts_by_taxonomy( $post->ID, 'destinations' );
while ( $related->have_posts() ): $related->the_post(); ?>
<div class="inner">
<a href="<?php get_permalink(); ?>"><?php the_post_thumbnail(); ?> </a>
<?php echo get_the_title(); ?>
</div>
<?php endwhile; ?>
I dont want to use any plugin, instead I want to add some code to my theme to do that.
Thank you all in advance for your time and answers! I would like to apologise but English is not my native language! Thank you for your understanding.