开发者

How do I Echo a variable in html?

I'm trying to include a variable within some existing code but my PHP skills are quite basic. I've looked around and can;t find anything I can reaidly apply 开发者_运维问答as a fix for this although I'm sure it's pretty simple.

The original code is:

<p class="ad-price"><?php if(get_post_meta($post->ID, 'price', true)) cp_get_price_legacy($post->ID); else cp_get_price($post->ID); ?></p>

and the code I'm trying to change it to (and think should be working) is:

<?php $yourtext = get_post_meta($post->ID, 'cp_pricing_period', TRUE); 
echo "<p class="ad-price"><?php if(get_post_meta($post->ID, 'price', true)) cp_get_price_legacy($post->ID); else cp_get_price($post->ID); ?> $yourtext</p>"; ?>

These changes are obviously wrong because it stops the whole file working. Can anyone shed light on where I'm getting this wrong?

Thanks


you have to escape the double quotes in your html

echo "<p class=\"ad-price\"><?php if(get_post_meta($post->ID, 'price', true)) cp_get_price_legacy($post->ID); else cp_get_price($post->ID); ?> $yourtext</p>"; ?>


Two problems. One, you've got mis-matched quotes within your echo statement:

echo "<p class="ad-price"><?php if(get_post_meta($post->ID, 'price', true))  etc....
               ^-here   ^--here

PHP will see those extra quotes as terminating the string, and then wonder what this ad-price directive is. This'll be a syntax error.

As well, once you get the string sorted out by escaping the embedded quotes:

echo "<p class=\"ad-price\">etc...."

you'll still end up with this not working. PHP will NOT see the <?php ... ?> within the string as PHP code to execute. it's within a string, so it'll be treated as part of the string and the PHP code will be echoed out to the user. In this case, you'd probably have write the whole thing more like this:

echo '<p class="ad-price">';
if(get_post_meta($post->ID, 'price', true)) {
     echo cp_get_price_legacy($post->ID);
} else { 
     echo cp_get_price($post->ID);
}
echo " $yourtext</p>";


Here, you have some syntax error (quotes not escaped and tags wrongly opend/closed). As a sidenote, "expanding" brackets makes your code more readable and it's easier to spot errors.

<?php
$yourtext = get_post_meta($post->ID, 'cp_pricing_period', TRUE); 

echo "<p class=\"ad-price\">";
if(get_post_meta($post->ID, 'price', true)) 
{
 cp_get_price_legacy($post->ID);
}
else 
{
  cp_get_price($post->ID); 
}

echo $yourtext."</p>"; 
?>


You need to put backslashes before the quotation marks in this statement:

echo "<p class="ad-price"><?php if(get_post_meta($post->ID, 'price', true))          cp_get_price_legacy($post->ID); else cp_get_price($post->ID); ?> $yourtext</p>"; ?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜