在 if 语句中插入 HTML


Insert HTML in if statement

<?php
if(get_field('member_only_content')){
    echo "do something";
}else{
    echo "do something else";
}
?>

如何在显示 HTML 代码的地方插入 HTML 代码"do something"?删除echo "do something";并粘贴HTML代码时,Wordpress网站崩溃。

关闭并打开 PHP 块,如下所示:

if(get_field('member_only_content')){
?>
    <html></html>
<?php
} else{
?>
    <html></html>
<?php
}

你也可以使用 PHP 的替代语法:

if(get_field('member_only_content')): ?>
    <html></html>
<?php else: ?>
    <html></html>
<?php endif;

像这样!

<?php
if(get_field('member_only_content')) : ?>
    <div>Html stuff</div>
<?php else : ?>
    <div>More Html stuff</div>
<?php endif;

将 HTML 放在字符串的位置。

<?php
if(get_field('member_only_content')){
    echo "<your>HTML here</your>";
}else{
    echo "<other>HTML</other>";
}
?>

你也可以打破PHP标签

<?php
if(get_field('member_only_content')){
    ?> 
    <your>HTML here</your>
    <?
}else{
    ?>
     <other>HTML</other>
    <?
}
     ?>

那是因为你把HTML代码放在php标签(<?php ?>(中。此标记中的文本被解释为 PHP 指令,因此它不会呈现 HTML。在 PHP 文件中呈现 HTML 有 2 种常规方法:

回显网页

<?php
    if (get_field ('member_only_content')) {
        echo "<span>Put HTML here</span>";
    }
    else {
        echo "<span>Put HTML here</span>";
    }
?>

将 HTML 放在 PHP 标记之外

<?php if (get_field ('member_only_content')): ?>
    <span>Put HTML here</span>
<?php else: ?>
    <span>Put HTML here</span>
<?php endif;?> 
或者

您可以使用<<<语句:>

echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;

直接来自 http://php.net/manual/en/function.echo.php

<?php
if(get_field('member_only_content')){
    echo "<div style='background-color: #888888'>This is a simple string between div's, make sure you've to be careful while inserting too many single and double quotes in this string as well as inline styles</div>";
}else{
    echo "do something else";
}
?>

在字符串中插入引号时要小心。

示例代码

echo("<h1>This is a sample</h1>");