Skip to content

Instantly share code, notes, and snippets.

@isotrope
Created July 18, 2016 17:18
Show Gist options
  • Save isotrope/53aaed0485c181386c20c25242b830ef to your computer and use it in GitHub Desktop.
Save isotrope/53aaed0485c181386c20c25242b830ef to your computer and use it in GitHub Desktop.
<?php
// Didn't want to recreate your class $this->return_message converted to $return_message
$clean_url = 'http://myurl.com';
$return_message = '<p>Saved: ' . $clean_url . '</p>';
// To localize it and be able to pass it a variable, you would use a placeholder like %d or %s (Digit / String)...
$return_message = '<p>' . sprintf( __( 'Saved: %s', 'website-cpt-text-domain' ), $clean_url ) . '</p>';
// that way, I can translate it as
//'Sauvegardé : %s'
//...or even...
//'%s a été sauvegardé' ($clean_url_value ' has been saved')
// Sometimes, you might need to feed it two variables.
// Imagine
$first_name = 'Jeff';
$last_name = 'Lebowski';
$return_message = '<p>' . sprintf( __( 'Your name is %s %s.', 'website-cpt-text-domain' ), $first_name, $last_name ) . '</p>';
// First of all, the above won't work. You need to 'number' your placeholders :
$return_message = '<p>' . sprintf( __( 'Your name is %1$s %2$s.', 'website-cpt-text-domain' ), $first_name, $last_name ) . '</p>';
// .. notice the #$.. 1$ and 2$ between the % and the type
// Now, it'll know to use the first var $first_name first and the second var $last_name second
// The other benefit is that the translator can actually move them around.
// Imagine a language where it's extremely impolite to say someone's name in that order.. (Bear with me, here...)
// I could actually translate it as 'Votre nom est is %2$s, %1$s' => 'Votre nom est Lebowski, Jeff.'
// One that isn't really necessary for your needs is the _n(), it's a bit special...
// ...it can take two translations: One for the singular and one for the plural :
$count = 1;
$return_message = '<p>' . sprintf( _n( 'I saved %d entry', 'I saved %d entries.', $count, 'website-cpt-text-domain' ), $count ) . '</p>';
// ..note that the $count var is passed to _n() **and** to sprintf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment