Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active February 28, 2023 22:38
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 westonruter/d99067473ad799deb099334a70bdf336 to your computer and use it in GitHub Desktop.
Save westonruter/d99067473ad799deb099334a70bdf336 to your computer and use it in GitHub Desktop.
<?php
/**
* @package Syntax_Highlighting_Code_Block
* @author Weston Ruter
* @link https://gist.github.com/westonruter/d99067473ad799deb099334a70bdf336
* @license GPL-2.0-or-later
* @copyright 2023 Google Inc.
*
* @wordpress-plugin
* Plugin Name: Code Block Copy Button
* Plugin URI: https://gist.github.com/westonruter/d99067473ad799deb099334a70bdf336
* Description: Add a copy button to all Code blocks.
* Version: 0.1.0
* Author: Weston Ruter
* Author URI: https://weston.ruter.net/
* License: GNU General Public License v2 (or later)
* License URI: http://www.gnu.org/licenses/gpl-2.0.html
*/
add_filter( 'render_block', static function ( $content, $block ) {
if ( 'core/code' !== $block['blockName'] || empty( $block['innerHTML'] ) ) {
return $content;
}
ob_start();
?>
<script>
navigator.clipboard.writeText( this.dataset.code ).then(
() => {
this.textContent = this.dataset.successLabel;
},
(err) => {
this.textContent = this.dataset.errorLabel;
console.error(err);
}
).finally( () => {
setTimeout(
() => {
this.textContent = this.dataset.defaultLabel;
},
3000
)
} )
</script>
<?php
$js = str_replace( [ '<script>', '</script>' ], '', ob_get_clean() );
$label = __( 'Copy Code', '...' );
$code = wp_strip_all_tags( $block['innerHTML'] );
$button = sprintf(
'<button data-code="%1$s" onclick="%2$s" data-default-label="%3$s" data-success-label="%4$s", data-error-label="%5$s">%3$s</button>',
esc_attr( $code ),
esc_attr( $js ),
esc_attr( $label ),
esc_attr__( 'Copied', '...' ),
esc_attr__( 'Copy Error', '...' ),
esc_html__( $label ),
);
return $content . "<p>$button</p>";
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment