NB: Make sure you do a back up of your theme, files and database before attempting the tutorials
Last modified : Sep 01 2022
Estimated reading time : 1 minute, 26 seconds - 121 words
Share the post "Display posts related of a taxonomy slug"
Display posts related of a taxonomy slug: With this tutorial, we will create a query that will display a list of post type or posts linked to a taxonomy’s slug.
With our example, we will create a taxonomy which represents an artist. Our Post Type will be viavideos.
With the example below, we will store the args and taxonmy inside a variable and fetch it with post ID.
We will now create our WordPress query for the viavideos Post Type, and then we’ll add the artist taxonomy’s tax_query.
Finally we’ll add a condition that excludes the ID of the currently viewed ID.(‘post__not_in’ => array ($post->ID)).
<?php
// get the custom post type's taxonomy terms
$taxonomyterms = wp_get_object_terms( $post->ID, 'artiste', array('fields' => 'ids') );
// arguments
$args = array(
//Change you Post Type or post for posts WordPress
'post_type' => 'viavideos',
'post_status' => 'publish',
'posts_per_page' => 3, // you may edit this number
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'artiste',
'field' => 'id',
'terms' => $taxonomyterms
)
),
'post__not_in' => array ($post->ID),
);
$related_items = new WP_Query( $args );
// loop over query
if ($related_items->have_posts()) : while ( $related_items->have_posts() ) : $related_items->the_post();
?>
//// Your loop
<?php endwhile; ?>
<?php endif; ?>Adapt this query to match your needs and add it inside your loop.