在WordPress中使用esc_html__()方法输出字符串加占位符变量

Tim*_*ius 4 php wordpress

在 WordPress 的显示中,我使用了该esc_html__()方法来转义字符串并添加变量以便在 HTML 输出中安全使用。

我的代码如下:

<?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; ?>
Run Code Online (Sandbox Code Playgroud)

但是我的变量没有输出到最终值,我得到的输出字符串是这样的:

底价

我之前尝试过$reserve_price是一个非空变量,但是 esc_html__() 没有将正确的信息输出到页面。

我不太确定这个原因。

Ruv*_*vee 6

“我之前尝试过 $reserve_price 是一个非空变量,但是 esc_html__() 没有将正确的信息输出到页面。”

您不能在函数中使用占位符esc_html__()。它仅检索给定文本的翻译并将其转义以便在 HTML 输出中安全使用。这意味着您可以用它来:

  • 转义 html 标记 + 翻译

但是,如果您需要:

  • 转义 html 标记 + 翻译 + 占位符

esc_html然后您可以使用,sprintf和函数的组合__(),如下所示:

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

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

这将输出:

在此输入图像描述

如果提供的文本没有任何 html 标签,那么它会是这样的:

$test_value = 5.7;

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

在此输入图像描述


现在,如果我们将相同的原则应用于您的代码片段,那么它将是这样的:

<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>
Run Code Online (Sandbox Code Playgroud)

如果你能让它工作,请告诉我!