NB: Make sure you do a back up of your theme, files and database before attempting the tutorials

Randomly Display Taxonomy Terms
Hard

---- Last modified : Oct 01 2022

Estimated reading time : 1 minute, 23 seconds - 183 words

With this tutorial, we’re going to show you how to display randomly display taxonomies. For example, we’ll create a Post Type called Event whose taxonomy will be Event Type. We consult an Event page and under its results, we want to randomly display additional taxonomy except for the one we’re currently viewing.

They are like similar terms, but random.

For our example:
Post Type: Events
Taxonomy: Event type (must be the same as the category name)
Template used: taxonomy-type-evenements.php

Thus we will create a query that will allow us to do so. We will use the get_terms function and add our args. Afterwards, we will get a random result and we will indicate how many results to return. To display the results, we close the loop with a foreach for every term.

We also must not forget to exclude the term we are currently consulting with the get_queried_object_id(); that we use with our variable before the get_terms.

Randomly Display Taxonomy Terms

<?php 
    //Get all terms 
	$currentid = get_queried_object_id(); 
	$terms = get_terms( array( 
	'taxonomy'      => 'type-evenements',
	'hide_empty'    => false,
	'exclude'       => array($currentid)
	) );
	// Randomize Term Array
	shuffle( $terms );
	// Grab Indices 0 - 5, 6 in total
	$randterms = array_slice( $terms, 0, 2 );
?>
<?php foreach ($randterms as $term) { ?>
<?php /// Votre div dynamique désirée ?>
<?php endforeach; wp_reset_postdata(); ?>

So by using get_terms, make sure to change the args for yours without adding any new ones.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>