Look at this horrible-to-look-at code from wordpress’s twentyten theme:
<?php
function twentyten_posted_on() {
printf( __( '<span class="%1$s">Posted on</span> %2$s <span class="meta-sep">by</span> %3$s', 'twentyten' ),
'meta-prep meta-prep-author',
sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><span class="entry-date">%3$s</span></a>',
get_permalink(),
esc_attr( get_the_time() ),
get_the_date()
),
sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s">%3$s</a></span>',
get_author_posts_url( get_the_author_meta( 'ID' ) ),
sprintf( esc_attr__( 'View all posts by %s', 'twentyten' ), get_the_author() ),
get_the_author()
)
);
}
?>
Why would anyone want to do that??
Why not do the following instead?
<?php
function twentyten_posted_on() {
?>
<span class="meta-prep meta-prep-author">Posted on</span>
<a href="<?php= get_permalink() ?>" title="<?php= esc_attr( get_the_time() ) ?>" rel="bookmark">
<span class="entry-date">get_the_date()</span>
</a>
<span class="meta-sep">by</span>
<span class="author vcard">
<a class="url fn n" href="<?php= get_author_posts_url( get_the_author_meta( 'ID' ) ) ?>" title="<?php= esc_attr__( 'View all posts by '.get_the_author() ) ?>"><?php= get_the_author() ?></a>
</span>
<?php
}
?>
The latter is much cleaner to me. Why would anyone use the first method instead? Is it just personal preference, or is there some functional benefit?
It’s written the way it is so it can be internationalized. You’ll see that, inside the call to
printf(), there’s a call to__(), which is WordPress’ translation function.This way, the translators can easily move the portions of each string around, by just moving the
%1$sparts, to comply with their language’s grammar and structure. Then, the translated formatting string is passed toprintf(), which can insert the appropriate variables.WordPress’ doc page on translation has some examples of the translator side of this (albeit with simpler strings).
Not all of what’s going on there is strictly necessary for the translation, but since they’re doing some things printf-style already, I guess the theory is that it’s easier to understand if it’s at least consistent.