Add PHP code inside printf method

I am modifying a WordPress theme by adding custom fields. One of the custom field is a dropdown list that I want to populate with array values from a separate function. I have found examples of this, but my problem is that I have to create dropdown inside a printf method, which means adding some php code inside printf, and I cannot figure out how to do it. I found a possible solution on Stack Overflow , which is to escape the single quotes, but I have not managed to do that properly. I cannot get away from the syntax errors, and for that reason, I am not able to go forward.

Here is the printf method that contains some html, which I need to populate with php that loops through array and uses values to populate dropdown. As I mentioned, array is defined in a separate function…

printf(
'<div class="cfwc-custom-field-wrapper">
<label for="custom_field_title">%s</label>
<select name="custom_field_title" id="custom_field_title">
		
            **add `php` here**

</select>
</div>',
esc_html( $title_select )
);

Most of the examples I found are about how to write PHP inside HTML, which is fairly easy with php tags. My question is how to do it inside a printf method, when you have to omit the single quotes?

I hope a fresh pair of eyes will help me with this.

Thanks in advance

printf accepts just a string as it’s first parameter. You could prepare this string before you use printf. There is no need to push everything into one statement which often is unreadable, even for yourself after a while.

<?php
$html = '<select>';
foreach($options as $option) {
    $html .= '<option>' . $option . '</option>'; // you could do this with sprintf too but i do not see the reason.
}
$html = '</select>';

printf($html); // i dont see why you want to  use printf? echo $html; is just fine
?>

Even a much better solution would be if you wrote a function that builds the options for you .

Thank you for the answer, that was helpful. I managed to populate the dropdown list with array created in the same function, and I changed the printf to echo.

Sponsor our Newsletter | Privacy Policy | Terms of Service