Skip to content

Instantly share code, notes, and snippets.

@wpsmith
Last active January 18, 2022 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpsmith/36bdeb2309dfd675bc6e3fbb309b753d to your computer and use it in GitHub Desktop.
Save wpsmith/36bdeb2309dfd675bc6e3fbb309b753d to your computer and use it in GitHub Desktop.
PHP/JS: Change title with typed text.
<?php
add_action( 'wp_enqueue_scripts', 'my_child_scripts' );
/**
* Add my scripts.
*/
function my_child_scripts() {
// Output typed.js from a CDN.
wp_enqueue_script( 'typed', 'https://cdn.jsdelivr.net/npm/typed.js@2.0.12', ['jquery'], '2.0.12', true );
// Change the strings to be whatever you want.
$strings_to_type = [
'fun',
'exciting',
];
$number_of_strings = count( $strings_to_type );
// See https://github.com/mattboldt/typed.js/#customization for all the settings.
$settings = [
'strings' => $strings_to_type,
'smartBackspace' => true,
'typeSpeed' => 30,
'backSpeed' => 50,
'backDelay' => 1000,
'loop' => true,
];
// Adds the settings object before.
// Create a JavaScript object called `typedSettings` which can be used for the next inline script.
// wp_json_encode( $settings ) outputs the PHP $settings object so JavaScript can understand it.
// Assign the $settings to `typedSettings` in the JavaScript global scope.
wp_add_inline_script(
'typed',
sprintf(
'var typedSettings = %s; typedSettings["preStringTyped"] = %s',
wp_json_encode( $settings ),
"
function(arrayPos, self) {
const numberOfStrings = $number_of_strings;
// The length of colors must equal to the same length as numberOfStrings.
const colorClass = [
'black',
'red',
'blue',
];
if (0 === arrayPos) {
jQuery('.typed-text').removeClass(colorClass[numberOfStrings - 1]);
} else {
jQuery('.typed-text').removeClass(colorClass[arrayPos - 1]);
}
jQuery('.typed-text').addClass(colorClass[arrayPos]);
}
"
),
'before'
);
// Instantiates the typed script with our settings object.
// According to the documentation, we are instantiating Typed JavaScript object on any HTML with a class of .typed-text applying our settings.
// Wrap in an immediately invoked function expression (IIFE) to prevent it from being placed in the global scope.
wp_add_inline_script( 'typed', '(function() {var typed = new Typed(".typed-text", typedSettings);})();' );
}
// Filter the title on the front page.
add_filter( 'the_title', function( $title, $id ) {
// Make sure we are on the front page and only changing the title we want.
if ( $id === get_the_ID() && is_front_page() ) {
// Only insert the typed text if "for professionals" exists.
return str_replace( 'for professionals', 'for<br/><span class="typed-text"></span><br/>professionals', $title );
}
return $title;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment