Created
July 20, 2015 00:36
-
-
Save mrbobbybryant/90f2c8b875e9ba385a6f to your computer and use it in GitHub Desktop.
sprintf examples
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$permalink = 'http://www.youtube.com'; | |
$id = 2; | |
$title = "My book title"; | |
$pub_date = 'January 15th, 2015'; | |
$city = "New York"; | |
$zipcode = '28475'; | |
$name = 'Bobby'; | |
$like = 'WordPress'; | |
//Use this: | |
echo sprintf( __( 'My name is %s and I like %s' ), $name, $like ); | |
echo '<br />'; | |
//Instead of this: | |
echo __( 'My name is ' . $name . ' and I like ' . $like ); | |
echo '<br />'; | |
//------------------------------------------------------- | |
//Use This | |
echo sprintf( '<a href="%s" id="%d">%s, %s</a>', | |
esc_url( $permalink ), | |
esc_attr( $id ), | |
esc_html( $title ), | |
esc_html( $pub_date ) | |
); | |
echo '<br />'; | |
//Instead of this: | |
echo '<a href="' . esc_url( $permalink ) . '" id="' . esc_attr( $id ) . '">' . esc_html( $title ). ', ' . esc_html( $pub_date) . '</a>'; | |
echo '<br />'; | |
//---------------------------------------------------- | |
//An example using argument swapping | |
echo sprintf( __( 'Your city is %1$s, and your zip code is %2$s.', 'my-text-domain' ), $city, $zipcode ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment