Skip to content

Instantly share code, notes, and snippets.

@kovshenin
Created July 10, 2012 07:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kovshenin/3081766 to your computer and use it in GitHub Desktop.
Save kovshenin/3081766 to your computer and use it in GitHub Desktop.
Yes, you can use printf and sprintf in WordPress too!
<?php
// Dirty, easy to miss a ' or " or .
echo '<a href="' . get_permalink() . '" class="link">' . get_the_title() . '</a>';
// Clean, easier to read
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title() );
// Almost as clean, and more secure, maybe a little paranoic :)
printf( '<a href="%s" class="link">%s</a>', esc_url( get_permalink() ), esc_html( get_the_title() ) );
@noeltock
Copy link

Good idea for one-liners, makes sense!

@jarretc
Copy link

jarretc commented Jul 10, 2012

I always thought it had to do with translations, but I guess not.

What is the exact use? Looked it up on php.net but still don't fully understand why it exists.

@kovshenin
Copy link
Author

@jarretc, yes it's used a lot with translations too, it's very convenient because it's so much easier to read, and you can move words around as well, like some languages say "%d comments" while others can say "comments: %d". These two functions exist in many other languages too, and I guess the "exact use" is, well, formatted output. I like to call it print/echo on steroids :D

Copy link

ghost commented Jul 10, 2012

Being somewhat novice at writing php, are there any exceptions when it's better to write something else?

In example, would it make any sense rewriting:

add_action( 'wp_head', 'cor_canonical_link' );
function cor_canonical_link() {
  global $paged;
  ?>
  <link href="<?php echo get_pagenum_link( $paged ); ?>" rel="canonical" />
  <?php
}

to

add_action( 'wp_head', 'cor_canonical_link' );
function cor_canonical_link() {
  global $paged;
  printf( '<link href="%s" rel="canonical" />' . "\n", get_pagenum_link( $paged ) );
}

@kovshenin
Copy link
Author

@corvannoorloos it's up to you, but the second snippet looks cleaner to me, but I'd go slightly further:

function cor_canonical_link() {
    printf( "<link href='%s' rel='canonical' />\n", get_pagenum_link( get_query_var( 'paged' ) ) );
}

Copy link

ghost commented Jul 10, 2012

@kovshenin thank you! I wasn't aware of this use of get_query_var.

Personally I prefer to use double quotes on the href and rel, but this definitely gives me something to work with.

@gauravpadia
Copy link

Good tip boss, thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment