Skip to content

Instantly share code, notes, and snippets.

@stephywells
Last active October 7, 2016 19:05
Show Gist options
  • Save stephywells/51e08738d11eedaa704e to your computer and use it in GitHub Desktop.
Save stephywells/51e08738d11eedaa704e to your computer and use it in GitHub Desktop.
Use the [cloud words="Awesome,Fabulous"] shortcode to create a cloud of words
<?php
/*
Plugin Name: S11 Word Cloud
Description: Use the [cloud words="Awesome,Fabulous"] shortcode to create a cloud of words
Version: 1.0
Author URI: http://strategy11.com
Author: Strategy11
*/
add_shortcode( 'cloud', 's11_word_cloud' );
function s11_word_cloud( $atts ) {
$atts = shortcode_atts( array(
'words' => 'Awesome, Fabulous',
'colors' => '#21759b, #d54e21, #464646',
), $atts );
$colors = explode( ',', $atts['colors'] );
$words = array_filter( explode( ',', $atts['words'] ) );
$words = array_map( 'strtolower', array_map( 'trim', $words ) );
$words = array_map( 'ucwords', $words );
$word_counts = array_count_values( $words );
$sorted = $word_counts;
arsort( $sorted );
$highest_count = reset( $sorted );
$max_size = 75;
$min_size = 10;
$step = absint( ( $max_size - $min_size ) / $highest_count );
$weighted = array();
foreach( $word_counts as $word => $count ) {
$weighted[ $word ] = $min_size + ( $step * $count );
}
$color_pointer = 0;
$all_words = array();
$cloud = '<ul class="s11cloud">';
foreach ( $weighted as $word => $size ) {
$all_words[] = '<li style="font-size:' . absint( $size ) .'px;color:' . esc_attr( $colors[ $color_pointer ] ) .'">' . trim( $word ) . '</li>';
$color_pointer++;
if ( ! isset( $colors[ $color_pointer ] ) ) {
$color_pointer = 0;
}
}
shuffle( $all_words );
$cloud .= implode( ' ', $all_words );
$cloud .= '</ul>';
s11_add_cloud_style( $cloud );
return $cloud;
}
function s11_add_cloud_style( &$cloud ) {
$cloud .= '<style>ul.s11cloud {
max-width: 500px;
padding: 30px 10px;
text-align:center;
margin:0 auto;
line-height: 1;
}
.s11cloud li{
display:inline-block;
list-style:none;
padding-right:3px;
}
</style>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment