Skip to content

Instantly share code, notes, and snippets.

@emiluzelac
Created March 30, 2017 21:47
Show Gist options
  • Save emiluzelac/32d53ab85c05cda846ad61590588a7bb to your computer and use it in GitHub Desktop.
Save emiluzelac/32d53ab85c05cda846ad61590588a7bb to your computer and use it in GitHub Desktop.
Escape translated strings
/**
* Escape translated strings with:
*/
__( ‘Hello world’, ‘text-domain’ ); _e( ‘Hello world’, ‘text-domain’ );.
/**
* If there is no HTML use:
*/
esc_html__( ‘Hello world’, ‘text-domain’ ); esc_html_e( ‘Hello world’, ‘text-domain’ );
/**
* When there's some HTML use:
*/
wp_kses( __( ‘Hello world’, ‘text-domain’ ), $allowed_html_array );
@joyously
Copy link

joyously commented May 10, 2018

Is there a better way to do this type of output which includes screen reader text (that I assume should not have the user HTML)?

edit_post_link(
	sprintf(
		wp_kses(
			/* translators: %s: Name of current post. Only visible to screen readers */
			__( 'Edit <span class="screen-reader-text">%s</span>', 'text-domain' ),
			array( 'span' => array( 'class' => array() ) )
		),
		get_the_title()
	),
	' <span class="edit-link">',
	'</span>'
);

@jrfnl
Copy link

jrfnl commented May 10, 2018

@joyously, I would suggest the following as an alternative way of writing that code:

$post_link_template = sprintf(
	/* translators: 1: Screen reader span open tag; 2: Name of current post, Only visible to screen readers; 3: Span close tag */
	esc_html__( 'Edit %1$s%2$s%3$s', 'text-domain' ),
	'<span class="screen-reader-text">',
	esc_html( get_the_title() ), // If you want to allow for some HTML in post titles, you could use `wp_kses_post()` as an alternative here.
	'</span'
);

edit_post_link(
	$post_link_template, // WPCS: XSS ok - text escaped properly just above.
	' <span class="edit-link">',
	'</span>'
);

@webplantmedia
Copy link

@joyously, I am currently doing this:

<?php
	edit_post_link(
		sprintf(
			'%1$s <span class="screen-reader-text">%2$s</span>',
			esc_html__( 'Edit', 'text-domain' ),
			get_the_title()
		),
		'<span class="edit-link">',
		'</span>'
	);
?>

@justintadlock
Copy link

@joyously - Here's an option if you're not wanting any tags from the title to appear:

<?php

edit_post_link(
	sprintf(
		// Translators: %s is the post title shown to screen readers.
		esc_html__( 'Edit%s' ),
		' <span class="screen-reader-text">' . wp_strip_all_tags( get_the_title() ) . '</span>'
	)
);

@joyously
Copy link

Thanks, I think @justintadlock has the best version since the HTML is of no use to screen readers.
But I've been thinking lately that the screen reader user might be better off with "Edit current post", rather than "Edit Hello World!".

@islamroshan
Copy link

i am currently working with codeigniter can i use html_escape?

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