【问题标题】:Put variable in quotes php [duplicate]将变量放在引号中php [重复]
【发布时间】:2021-05-01 03:09:41
【问题描述】:

我想将带有产品 ID 的变量放在 html 引号的引号中。

if ( ! function_exists( 'woocommerce_template_loop_product_link_open' ) ) {
    /**
     * Insert the opening anchor tag for products in the loop.
     */
    function woocommerce_template_loop_product_link_open() {
        global $product;
        $id = $product->get_id();
        $link = apply_filters( 'woocommerce_loop_product_link', get_the_permalink(), $product );

        echo '<a href="#" class="yith-wcqv-button" data-product_id="$id">';
    }
}

$id 应该在 data-product_id="$id" 但我不知道该怎么做

【问题讨论】:

    标签: php html wordpress string woocommerce


    【解决方案1】:

    字符串插值需要双引号。你已经很接近了。

    // OLD
    echo '<a href="#" class="yith-wcqv-button" data-product_id="$id">';
    
    // NEW
    echo "<a href=\"#\" class=\"yith-wcqv-button\" data-product_id=\"$id\">";
    

    【讨论】:

      【解决方案2】:

      我们有不同的方法来做到这一点。

      <?php
      $id = 321;
      
      // Concatenation operator
      echo '<a href="#" class="yith-wcqv-button" data-product_id="' . $id . '">';
      
      // sprintf return a string formatted. It's very common on C code
      echo sprintf('<a href="#" class="yith-wcqv-button" data-product_id="%d">', $id);
      
      // heredoc notation
      echo  <<<STR
      <a href="#" class="yith-wcqv-button" data-product_id="$id">
      STR;
      
      // escaping double quotes.
      echo "<a href=\"#\" class=\"yith-wcqv-button\" data-product_id=\"$id\">";
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-06
        • 1970-01-01
        • 2020-02-14
        • 2012-06-28
        • 1970-01-01
        • 1970-01-01
        • 2015-03-09
        • 2016-07-17
        相关资源
        最近更新 更多