0
votes

I have a website that shows online stores as posts, these stores can be attached to multiple brands which is a custom taxonomy.

Some of the stores have 20 brands so I would like to random show 5 brands on the store post.

I found the following code which returns 5 random brands (Displaying random Taxonomy terms in Wordpress)

<?php

$max = 5; //number of categories to display
$taxonomy = 'brands';
$terms = get_terms($taxonomy, 'orderby=name&order= ASC&hide_empty=0');

// Random order
shuffle($terms);

// Get first $max items
$terms = array_slice($terms, 0, $max);

// Sort by name
usort($terms, function($a, $b){
return strcasecmp($a->name, $b->name);
});

// Echo random terms sorted alphabetically
if ($terms) {
foreach($terms as $term) {
echo '<a href="' .get_term_link( $term, $taxonomy ) . '" title="' .  
sprintf( __( "View all posts in %s" ), $term->name ) . '" ' . '>' . $term- 
>name.'</a> ';
}
}?>

It however seems to get 5 random brands from all posts and not the current one.

Any ideas how to make this work only for taxonomies (brands) attached to the current post.

Thanks Richard

1
i think you taxonomy is common for all post type. please provide you all custom post type and taxonomy names.dev_ramiz_1707
i have a custom taxonomy of brand and only use standard post type. (no custom posts used)Richard Ascough
add code of custom post type and taxonomydev_ramiz_1707

1 Answers

0
votes

Your code is always saying to get taxonomy terms but does not specify that it should relate to the current post ID. This line should help:

$taxonomies=get_taxonomies('','names'); wp_get_post_terms($post->ID, $taxonomies, array("fields" => "names"));

Referencing this q&a: https://wordpress.stackexchange.com/questions/162175/get-taxonomy-names-by-post-id