回显变量中的变量

时间:2016-02-17 19:15:44

标签: php wordpress concatenation

我试图找出如何在变量内回显变量。

下面这段代码显然无效,因为我没有回应变量

$tweet = get_field('tweet_msg'); //this is getting the string inputted by user in the custom field
$tweet_intent = '<div><a href="https://twitter.com/intent/tweet?text="'.$tweet.'">TEST</a> </div>';

但是当我做PHP时会抛出一个错误,说出意想不到的回声:

$tweet_intent = '<div style="margin-bottom:15px;"><a href="https://twitter.com/intent/tweet?text="'.echo $tweet.'">TEST</a> </div>';

完整代码:

add_filter( 'the_content', 'prefix_insert_post_ads' );

function prefix_insert_post_ads( $content ) {
  $tweet = get_field('tweet_msg');
  $tweet_intent = '<div style="margin-bottom:15px;"><a href="https://twitter.com/intent/tweet?text="'.$tweet.'">TEST</a> </div>';

  if ( is_single() && ! is_admin() ) {
    return prefix_insert_after_paragraph( $tweet_intent, 2, $content );
  }

  return $content;
}

// Parent Function that makes the magic happen

function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
  $closing_p = '</p>';
  $paragraphs = explode( $closing_p, $content );
  foreach ($paragraphs as $index => $paragraph) {

    if ( trim( $paragraph ) ) {        $paragraphs[$index] .= $closing_p;
    }
    if ( $paragraph_id == $index + 1 ) {
      $paragraphs[$index] .= $insertion;
    }
  }     return implode( '', $paragraphs );
}

1 个答案:

答案 0 :(得分:5)

问题在于<a href>语法 假设在get_field()之后,$tweet的值为“Hello-World”,您的代码为:

$tweet_intent = '<div style="margin-bottom:15px;"><a href="https://twitter.com/intent/tweet?text="'.$tweet.'">TEST</a> </div>';

输入$tweet_intent此字符串:

(...)<a href="https://twitter.com/intent/tweet?text="Hello-World">TEST</a> </div>
             └──────────────────────────────────────┘     

如您所见,href的引号在 $tweet输出之前已关闭

您必须以这种方式更改代码:

$tweet = get_field( 'tweet_msg' );
$tweet = rawurlencode( $tweet ); // only if encoding is not performed by get_field 
$tweet_intent = '
    <div style="margin-bottom:15px;">
         <a href="https://twitter.com/intent/tweet?text='.$tweet.'">TEST</a>
    </div>';