5

I have seen the token %1$ and similar ones more often in the WordPress code lately, but I can't figure out what it means. Here an example:

sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),

Does anyone know what it means?

1
14

Read the PHP docs on sprintf().

  • %s is just a placeholder for a string
  • %d is just a placeholder for a number

So an example of sprintf would look like this:

$variable = sprintf(
    'The %s ran down the %s',   // String with placeholders
    'dog',      // Placed in the first %s placeholder
    'street'    // Placed in the second %s placeholder
);

Which will return a string to our variable $variable:

The dog ran down the street

By numbering the placeholders it's both a developer-friendly way to quickly tell which following string will be placed where. It also allows us to reuse a string. Let's take another example with numbered placeholders:

$variable = sprintf(
    'The %1$s ran down the %2$s. The %2$s was made of %3$s',    // String with placeholders
    'dog',      // Will always be used in %1$s placeholder
    'street',   // Will always be used in %2$s placeholder
    'gravel'    // Will always be used in %3$s placeholder
);

Which will return a string to our variable $variable:

The dog ran down the street. The street was made of gravel

Finally, the __() function let's us translate strings passed to it. By passing __() placeholders, and then passing that whole string to sprintf(), we can translate whatever is passed to the translating function allowing us to make our string and application a bit more dynamic.

0
7

It's not a WordPress thing, it's a PHP thing. %1$s, %2$s, etc., are placeholders for variables in a formatted string returned by sprintf() (or printed by printf()).

The 1$ indicates it's the first variable, 2$ would be the second, and so forth. The s indicates it's a string variable. Other options exist (eg, d would indicate an integer).

The example you give is incomplete: it's certainly something like this in its entirety:

sprintf( __( '%1$s is deprecated. Use %2$s instead.' ),
$string_1,
$string_2 );

Not the answer you're looking for? Browse other questions tagged or ask your own question.