Home > database >  Use esc_html__() method to output string plus a placeholder variable in WordPress
Use esc_html__() method to output string plus a placeholder variable in WordPress

Time:12-03

In a display of wordpress, I used the esc_html__() method to escape the string and add variables for safe use in HTML output.

My code is as follows:

<?php
global  $product, $post;
$posts_id = $product->get_id(); 
$reserve_price = get_post_meta($posts_id, '_auction_reserved_price', true);

if ($product->is_reserved() === true && $product->is_reserve_met() === false) : ?>

<p class="reserve hold"  data-auction-id="<?php echo esc_attr( $product->get_id() ); ?>">
    <?php echo apply_filters('reserve_bid_text', esc_html__('Reserve price has not been met, needed to enter $ %s or more', 'wc_simple_auctions', $reserve_price)); ?>
</p>

<?php endif; ?>

But my variable is not output to the final value, the output string I get is this:

reserve price

I tried before $reserve_price is a non-empty variable, but esc_html__() doesn't output the correct information to the page.

I am not quite sure about this reason.

CodePudding user response:

"I tried before $reserve_price is a non-empty variable, but esc_html__() doesn't output the correct information to the page."

You can not use placeholders in esc_html__() function. It only retrieves the translation of a given text and escapes it for safe use in HTML output. Which means you could use it to:

  • Escape html markups translation

However, if you would need to:

  • Escape html markups translation placeholder(s)

Then you could use the combination of esc_html, sprintf and __() functions, like so:

$test_value = '<strong>5.7<strong>';

echo esc_html(
       sprintf(
         __('This is a test for %s', 'your-text-domain'),
         $test_value
       )
     )

Which will output this:

enter image description here

And if the provided text does not have any html tag(s), then it'd be something like this:

$test_value = 5.7;

echo esc_html(
       sprintf(
         __('This is a test for %s', 'your-text-domain'),
         $test_value
       )
     )

enter image description here


Now, if we apply the same principles to your snippet, then it would be something like this:

<p class='reserve hold' data-auction-id='<?php echo esc_attr($product->get_id()); ?>'>
    <?php
    echo apply_filters(
        'reserve_bid_text',
        esc_html(
            sprintf(
                __('Reserve price has not been met, needed to enter $ %s or more', 'wc_simple_auctions'),
                $reserve_price
            )
        )
    );
    ?>
</p>

Let me know if you could get it to work!

  • Related