I’m trying to figure out how to echo a variable inside a variable.
This code below doesn’t obviously work because I’m not echoing the variable
$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>';
but when ever I do PHP throws an error saying unexpected echo:
$tweet_intent = '<div style="margin-bottom:15px;"><a href="https://twitter.com/intent/tweet?text="'.echo $tweet.'">TEST</a> </div>';
Full code:
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 );
}
The problem reside in your
<a href>
syntax.Assuming that, after
get_field()
, the value of$tweet
is ‘Hello-World’, your code:put in
$tweet_intent
this string:As you can see, the quotation marks of
href
are closed before$tweet
output.You have to change your code in this way: