0

I am trying to display a list of tags. I want to display 6 tags but random tags. Not post tags but tags from the entire site.

<?php
$number_to_show = 10;
$tags = wp_tag_cloud( array(
                    'taxonomy' => 'post_tag',
                    'format' => 'array',
                    'order' => 'RAND',
                    'number' => 0,
                    'smallest' => '10',
                    'largest' => '10',
                    'echo' => 0,
                    )
                 );

if ($tags) {
$max = ($number_to_show < sizeof($tags)) ? $number_to_show : sizeof($tags);
echo '<ul class="wp-tag-cloud">';
for ($i=0; $i < $max ; ++$i ) {
  echo "<li>{$tags[$i]}</li>";
}
echo '</ul>';
}
?>

I'm not very familiar with the codex/functions but I am trying my best to understand.

I want the tags to look this this via html

 <a class="class-name" href="tag-permalink"> <h3>Tag Name</h3></a> 

no ul or li list

I even tried this and it didn't work

<?php
$number_to_show = 6;
$tags = get_the_tags( array (
                    'taxonomy' => 'post_tag',
                    'format' => 'array',
                    'order' => 'RAND',
                    'number' => 0,
                    'echo' => 0,
                    )
                 );

 if ($tags) {
 foreach($tags as $tag){
    echo '<a href="'.get_tag_link($tag->term_id).'" rel="tag" class="dummy-   media-object"><h3>'.$tag->name.'</h3></a>';
} ?>

How can i resolve this

1

Try this:

$args = array(
    'taxonomy'   => 'post_tag',
    'hide_empty' => 0
);
$tags = get_terms( $args );
$class_name = 'my-custom-class-name';

if ( ! empty( $tags ) && ! is_wp_error( $tags ) ) {
    shuffle( $tags );   
    foreach( array_slice( $tags, 0, 6 ) as $tag ) {
        printf( '<a class="%1$s" href="%2$s">%3$s</a>',
            sanitize_html_class( $class_name ),
            get_tag_link( $tag->term_id ),
            sprintf( __( '%s') , $tag->name )
        );
    }
}

Since there isn't a RAND order option in get_terms() or get_the_tags(), what this does is:

  • Get all tags from the post_tags taxonomy
  • Shuffle the resulting array.
  • Slice the resulting array to 6 entries
  • Build links with your custom class
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.