Skip to content

Instantly share code, notes, and snippets.

@seezee
Last active November 17, 2021 22:28
Show Gist options
  • Save seezee/4d1a4899983b8e0b1ed4eeb30994ed1a to your computer and use it in GitHub Desktop.
Save seezee/4d1a4899983b8e0b1ed4eeb30994ed1a to your computer and use it in GitHub Desktop.
2 different ways to add rel="noopener noreferrer" to linked images in WordPress. Could be improved with a check for external links so we can also add "external".
<?php
/**
* Plugin Name: Add Rel to Images
* Description: Add rel="noopener noreferrer" to linked images.
*
* @package There is no package.
*/
/**
* With jQuery.
*/
function my_plugin_inline_script() {
wp_add_inline_script( 'jquery', 'jQuery( document ).ready( function( $ ) { $(".external").each(function() { $(".external a").attr("rel", "external noopener") }); });' );
}
add_action( 'wp_enqueue_scripts', 'my_plugin_inline_script' );
/**
* Vanilla JavaScript
*/
wp_register_script( 'set-rel', '', array(), '1.0.0', true );
wp_enqueue_script( 'set-rel' );
wp_add_inline_script( 'set-rel', 'document.querySelectorAll(".external a").forEach((el) => { el.setAttribute("rel", "external noopener"); });' );
@seezee
Copy link
Author

seezee commented Jun 17, 2021

Use with class "external", e.g.,

<div class="external"><a href="" target="_blank"><img src="/path/to/img" width="" height="" alt=""></a></div>

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