Add inline CSS and JavaScript in WordPress

/**
 * Add inline style. To be used in `wp_enqueue_scripts` or `admin_enqueue_scripts`.
 *
 * @param string $data String containing the CSS styles to be added. Without the `<style>` tags.
 *
 * @return bool True on success, false on failure.
 *
 * @see https://wpcodebook.com/add-inline-css-and-javascript-in-wordpress/
 * @see https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
 * @see https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
 * @see https://developer.wordpress.org/reference/functions/wp_register_style/
 * @see https://developer.wordpress.org/reference/functions/wp_enqueue_style/
 * @see https://developer.wordpress.org/reference/functions/wp_add_inline_style/
 */
function wpcodebook_add_inline_style( $data ) {
	wp_register_style(
		'wpcodebook',
		false,
		array(),
		'1.0.0'
	);

	wp_enqueue_style( 'wpcodebook' );

	return wp_add_inline_style(
		'wpcodebook',
		$data
	);
}

/**
 * Add inline script. To be used in `wp_enqueue_scripts` or `admin_enqueue_scripts`.
 *
 * @param string $data String containing the JavaScript to be added. Without the `<script>` tags.
 *
 * @return bool True on success, false on failure.
 *
 * @see https://wpcodebook.com/add-inline-css-and-javascript-in-wordpress/
 * @see https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/
 * @see https://developer.wordpress.org/reference/hooks/admin_enqueue_scripts/
 * @see https://developer.wordpress.org/reference/functions/wp_register_script/
 * @see https://developer.wordpress.org/reference/functions/wp_enqueue_script/
 * @see https://developer.wordpress.org/reference/functions/wp_add_inline_script/
 */
function wpcodebook_add_inline_script( $data ) {
	wp_register_script(
		'wpcodebook',
		false,
		array(),
		'1.0.0',
		true
	);

	wp_enqueue_script( 'wpcodebook' );

	return wp_add_inline_script(
		'wpcodebook',
		$data
	);
}

Leave a Comment