• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

WP SITES

2662

Original Genesis Tutorials & 5000+ Guaranteed Code

Snippets

  • Support
  • Newsletter
  • Videos
  • Log in

Premium Member? - Request custom code

sprintf

sprintf is similar to printf however is used to return the result as a value for a variable to be used later rather than output immediately.

Here’s the difference you can test in your child themes functions file.

sprintf
add_action('loop_start','sprintf_example' );
function sprintf_example() {		
$output = sprintf('%s World', 'Hello' ); 
echo $output;
}
printf
add_action('loop_start','printf_test' );
function printf_test() {		
	printf('%s World', 'Hello' ); 
}

Both code snippets produce exactly the same result. The only difference is sprintf returns the value for the variable and printf outputs directly.

You can also write the code using sprintf like this:

add_action('loop_start','sprintf_example1' );
function sprintf_example1() {
$text = "Hello";		
$output = sprintf('%s World', $text ); 
echo $output;
}

And this:

add_action('genesis_after_header','sprintf_example2' );
function sprintf_example2() {
    $link = get_permalink();
    $text = "Hello";		
    $output = sprintf('%s World', $text ); 
printf( '<a href="%s">' . $output . '</a>', $link );
}

Or this:

add_action('wp_head','sprintf_example3' );
function sprintf_example3() {
    $link = get_permalink();
    $text = "sprintf";		
    $output = sprintf('%s Example', $text ); 
printf( '<a href="%s">%s</a>', $link, $output );
}

Related PHP Code

  • printf
  • Variable
  • 12 Code Examples for using sprintf & sprintf

PHP Functions

Reader Interactions

Leave a Reply Cancel reply

You must be logged in to post a comment.

Primary Sidebar

PHP Code

template_include

get_body_class

if else

array

class_exists

foreach

sprintf

add_action

printf

variable

Advertise · WPEngine · Genesis · Log in

  • How Premium Membership Works
  • Sign Up
  • Support
  • Subscription Details/Invoice
  • Tagged Tutorials
  • Access-Download Problems