Skip to content

Instantly share code, notes, and snippets.

@westonruter
Last active May 1, 2019 18:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save westonruter/3cf877833a8f94776536e3f90bb30ea2 to your computer and use it in GitHub Desktop.
Save westonruter/3cf877833a8f94776536e3f90bb30ea2 to your computer and use it in GitHub Desktop.
<?php
/**
* Plugin Name: Embeds in Comments with AMP Support
* Plugin URI: https://gist.github.com/westonruter/3cf877833a8f94776536e3f90bb30ea2
* Author Name: Weston Ruter
* Author URI: https://weston.ruter.net/
*/
namespace Embeds_In_Comments;
/**
* Force balanced tags with support for AMP custom elements.
*
* The `force_balance_tags` function is not aware of custom elements (which contain hyphens),
* so this strips the first hyphen before doing force_balance_tags() and restores it after.
* Note that this does not yet support AMP tags that have multiple hyphens.
*
* @see force_balance_tags()
*
* @param string $content Content.
* @return string Content.
*/
function force_balance_tags( $content ) {
$content = preg_replace( ':<(/?)amp-:', '<$1amp', $content );
$content = \force_balance_tags( $content );
return preg_replace( ':<(/?)amp(?!-):', '<$1amp-', $content );
}
remove_filter( 'comment_text', 'force_balance_tags', 25 );
add_filter( 'comment_text', __NAMESPACE__ . '\force_balance_tags', 25 );
/**
* Add embeds to comments.
*
* Props sheabunge.
*
* @link https://gist.github.com/sheabunge/6018753
*
* @param string $comment_text Comment text.
* @return string Comment text.
*/
function add_embeds_to_comment_text( $comment_text ) {
/** @global \WP_Embed $wp_embed */
global $wp_embed;
/* Automatic discovery would be a security risk, safety first */
add_filter( 'embed_oembed_discover', '__return_false', 999 );
$comment_text = $wp_embed->run_shortcode( $comment_text );
$comment_text = $wp_embed->autoembed( $comment_text );
/* ...but don't break your posts if you use it */
remove_filter( 'embed_oembed_discover', '__return_false', 999 );
return $comment_text;
}
add_filter( 'comment_text', __NAMESPACE__ . '\add_embeds_to_comment_text', 8 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment