Skip to content

Instantly share code, notes, and snippets.

@ironprogrammer
Last active February 4, 2023 01:36
Show Gist options
  • Save ironprogrammer/372bfcbf71ba1ea8af2a993fd602567d to your computer and use it in GitHub Desktop.
Save ironprogrammer/372bfcbf71ba1ea8af2a993fd602567d to your computer and use it in GitHub Desktop.
Trac 57575 Test Plugin
<?php
/**
* Plugin Name: Test for Trac 57575
* Plugin URI: https://core.trac.wordpress.org/ticket/57575
* Description: This plugin modifies links to external URLs in `core/paragraph` blocks using the HTML Tag Processor.
* Requires at least: 6.2
* Requires PHP: 5.6
* Version: 1.0.0
* Author: WordPress Core Contributors
*
* To install and test:
* 1. Copy this file into your test site's wp-content/plugins/ directory.
* 2. Enable the plugin.
* 3. Create a post, and insert a paragraph block. Add some text.
* 4. In the paragraph text, add hyperlinks to internal and external URLs, then publish the post.
* 5. View the post.
* 6. Observe the rendered output, as well as the modified markup (via View Source).
*
* To uninstall:
* Disable and remove this file from wp-content/plugins/.
*/
// Only process `core/paragraph` blocks.
add_filter( 'render_block_core/paragraph', 'test_trac_57575_plugin', 10, 2 );
function test_trac_57575_plugin( $block_content, $block ) {
// Avoid fatal error if not installed on latest `trunk`.
if ( ! class_exists( 'WP_HTML_Tag_Processor' ) ) {
return $block_content;
}
$site_url = get_site_url();
$tags = new WP_HTML_Tag_Processor( $block_content );
// Process anchor tags.
while ( $tags->next_tag( 'a' ) ) {
$href = $tags->get_attribute( 'href' );
// Skip tag if it's not linked to an external URL.
if (
$href
&& '#' !== $href[0]
&& ! str_starts_with( $href, $site_url )
) {
// Style external links.
$tags->add_class( 'dashicons-before' );
$tags->add_class( 'dashicons-external' );
$tags->set_attribute( 'style', 'color:var(--wp--preset--color--contrast);font-weight:bold;' );
}
}
return $tags->get_updated_html();
}
@ironprogrammer
Copy link
Author

Added a class check to prevent an annoying fatal if you haven't pulled down the latest trunk.

If you don't see external link styles modified by this plugin, please confirm whether you're working from the latest wordpress-develop:trunk.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment