Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress Shortcode to Rotate Keywords in a Sentence
<?php
// Add to your theme's functions.php file
// Usage: [rotatewords firstterm="Known" terms="Engaged, Retained, Loyal, Advocates" delay="1500" fadeout="500" fadein="100"]Are Your Customers Known?[/rotatewords]
// The first term you use will be rotated through.
wp_enqueue_script("jquery");
function dknm_keyword_rotate($atts, $content = "") {
$atts = shortcode_atts( array(
'firstterm' => '',
'terms' => '',
'delay' => 1500,
'fadeout' => 500,
'fadein' => 100
), $atts, 'rotatewords' );
$terms = explode(",", $atts['terms']);
$comma_separated = implode('","', $terms);
$comma_separated = '"'.$comma_separated.'"';
$firstterm = '<span>'.$atts['firstterm'].'</span>';
$content = str_replace($atts['firstterm'], $firstterm, $content);
$rotatewords = '<div id="dknm-rotatekeywords">'.$content.'</div>';
$rotatewords .= '<script type="text/javascript">jQuery(function($) {';
$rotatewords .= '$(document).ready(function() {';
$rotatewords .= 'var items = ['.$comma_separated.'],';
$rotatewords .= '$text = $(\'#dknm-rotatekeywords span\' ),';
$rotatewords .= 'delay = '.$atts['delay'].';';
$rotatewords .= 'function loop ( delay ) {
$.each( items, function ( i, elm ){
$text.delay( delay ).fadeOut('.$atts['fadeout'].');
$text.queue(function(){
$text.html( items[i] );
$text.dequeue();
});
$text.fadeIn('.$atts['fadein'].');
$text.queue(function(){
if ( i == items.length -1 ) {
loop(delay);
}
$text.dequeue();
});
});
}
loop( delay );
});
});</script>';
return $rotatewords;
}
add_shortcode('rotatewords', 'dknm_keyword_rotate');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.