Home > other >  How to sort tag clouds alphabetically in WordPress
How to sort tag clouds alphabetically in WordPress

Time:04-18

I am adding a new "Zone" tag through the WordPress admin, it should be at the very end, since the letter Z is the last in the alphabet. But my tag "Zone" is displayed on the page at the very beginning of the list in the tag cloud.

My code for displaying tags:

<article > 
 <p >Tags Cloud:</p>
 <div >
 
 <?php 
 wp_tag_cloud( [
    'smallest'  => 14,
    'largest'   => 14,
    'unit'      => 'pt',
    'number'    => 0,
    'format'    => 'flat',
    'separator' => "",
    'orderby'   => 'name',
    'order'     => 'ASC',
    'exclude'   => null,
    'include'   => null,
    'link'      => 'view',
    'taxonomy'  => 'post_tag',
    'echo'      => true,
    'topic_count_text_callback' => 'default_topic_count_text',  
] );
?>
 
</div>
 </article>

CodePudding user response:

First we use wp_tag_cloud() to get the tags associated with the post. Then, pass in a few parameters. First, the 'format' parameter makes the tags into an array so we can loop through them. then, we set it to not echo as we want to save it into a variable. You would then need to use the asort() function. This is a function inside of PHP, so it isn't exclusive to WordPress.

Here is more parameters that can be passed into the function: https://developer.wordpress.org/reference/functions/wp_generate_tag_cloud/

Let me know if you have any questions! :)

$tagsExample = wp_tag_cloud(
    ['format' => 'array',
        'echo' => false
    ]); 
    
asort($tagsExample);

foreach($tagsExample as $tag) {
    echo $tag;
}
  • Related