Don’t be shy to use the
sprintf functions with WordPress. It makes code much easier to read. Take a look at the following examples.
echo '<a href="' . get_permalink() . '" class="link">' . get_the_title() . '</a>';
It looks quite dirty and it’s very easy to miss a quote or double-quote. Here’s one that looks a lot cleaner and easier to read:
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title() );
And here’s a slightly less clean, but more secure example:
printf( '<a href="%s" class="link">%s</a>', esc_url( get_permalink() ), esc_html( get_the_title() ) );
You might think escaping the permalink and the post title is not necessary, and you’re right. However, it’s considered best practice to escape as late as possible, which is often right before the output. Here’s a more complex example, taken from the Twenty Twelve theme:
$date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s" pubdate>%4$s</time></a>',
esc_url( get_permalink() ),
esc_attr( get_the_time() ),
esc_attr( get_the_date( 'c' ) ),
esc_html( get_the_date() )
It also makes use of argument swapping, which is very common when working with translation functions, mainly because RTL languages would need to swap things around. It’s also very convenient to read when there are two or more placeholders.
You can learn more about
sprintf (with a bunch of cool examples) in this article, and about escaping and data validation right here.
Thanks for reading and have a great day!