【问题标题】:how to use string vars in echo function如何在 echo 函数中使用字符串变量
【发布时间】:2015-05-02 13:28:45
【问题描述】:

我想在 word press 中的 header.php 模板中使用此代码来使用 ACF 插件字段。 但它不起作用。例如href 属性不起作用。

这是我的代码:

echo '<div align="center">';
//Rule Adress
if (the_field("rule") != 'http://' || the_field("rule") != '') {
    echo '<a href="' . the_field('rule') . '" role="button" class="Button Button--error" title="Rules" rel="nofollow" target="_blank"><i class="fa fa-fw fa-check"></i>Rules</a>';
}
//Cost
if (the_field("cost") != '0' || the_field("rule") != '') {
    echo '<a role="button" class="Button Button--info" style="cursor: default;"><i class="fa fa-fw fa-shopping-cart"></i>Cost: ' . the_field('cost') . ' Dolor</a>';
}
//Demo
if (the_field("demo") != 'http://' || the_field("demo") != '') {
    echo '<a href="' . the_field('demo') . '" role="button" class="Button Button--primary" title="Demo" rel="nofollow" target="_blank"><i class="fa fa-fw fa-heart"></i>Demo</a>';
} else {
    echo '<a role="button" class="Button Button--primary" title="Demo" style="cursor: default;"><i class="fa fa-fw fa-heart"></i>Demo</a>';
}
//Shots
if (the_field("shots") != 'http://' || the_field("shots") != '') {
    echo '<a href="' . the_field('shots') . '" role="button" class="Button Button--warning" title="Shots" rel="nofollow" target="_blank"><i class="fa fa-fw fa-desktop"></i>Shots</a>';
} else {
    echo '<a role="button" class="Button Button--warning" title="Shots" style="cursor: default;"><i class="fa fa-fw fa-desktop"></i>Shots</a>';
}
echo '</div">';

is-productrulecostdemoshot 字段是我在 wp-admin 中定义的字段。

请帮我解决这个问题。

【问题讨论】:

    标签: php string wordpress advanced-custom-fields


    【解决方案1】:

    不要在if 语句中使用the_field('field'),而是使用get_field('field') 将其作为值而不是对象返回。

    例如:

    <?php if (get_field("rule") != 'http://' || get_field("rule") != '') { ?>
        <a href="<?php the_field('rule'); ?>" role="button" class="Button Button--error" title="Rules" rel="nofollow" target="_blank"><i class="fa fa-fw fa-check"></i>Rules</a>
    <?php } ?>
    

    您还可以将这个表达式缩短如下:

    <?php 
        $rule = get_field("rule")
        if($rule || $rule != 'http://') { ?>
            <a href="<?php echo $rule; ?>" role="button" class="Button Button--error" title="Rules" rel="nofollow" target="_blank"><i class="fa fa-fw fa-check"></i>Rules</a>
    <?php } ?>
    

    【讨论】:

    • 谢谢@asherstoppard。我不能将 the_field() 与“if”语句一起使用?这段代码是否正常工作?
    • 完全没有问题,修改后一切正常吗?
    猜你喜欢
    • 2019-08-19
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多