首页 > 解决方案 > 如何将这些自定义字段组合为 wordpress 中的链接

问题描述

我知道可能有更好的方法来做到这一点。我有大约 5 个自定义字段需要组合

<?php 
$link = get_field('twitter');
if( $link ): ?>
    <a class="button" href="<?php echo esc_url( $link ); ?>"><i class="fab fa-twitter"></i></a>
<?php endif; ?>


        <?php 
$link = get_field('linkedin');
if( $link ): ?>
    <a class="button" href="<?php echo esc_url( $link ); ?>"><i class="fab fa-linkedin-in"></i></a>
<?php endif; ?>

标签: phpwordpress

解决方案


你可以做这样的事情。您只需根据需要向链接数组添加任意数量的条目。这样你就可以避免重复很多代码。

$links = [
    ["url" => get_field('twitter'), "icon" => "fa-twitter"],
    ["url" => get_field('linkedin'), "icon" => "fa-linkedin-in"]
];

foreach ($links as $link) {
    if ($link["url"]) {
        echo '<a class="button" href="' . esc_url($link["url"]) . '"><i class="fab ' . $link["icon"] . '"></i></a>';
    }
}

添加电话号码链接需要稍微不同的方法,因为您不应该使用用于检查和清理 url 的 esc_url 函数

$phones = [
    ["number" => get_field('phone'), "icon" => "fa-phone"],
    ["number" => get_field('mobile'), "icon" => "fa-mobile"]
];

foreach ($phones as $phone) {
    if ($phone["number"]) {
        $onlyNumber = preg_replace('/[^0-9]/', '', $phone["number"]);
        echo '<a target="_blank" class="button-social-team" href="tel:' . $onlyNumber . '"><i class="fas ' . $phone["icon"] . '"></i></a>';
    }
}

onlyNumber 行旨在通过仅允许其中的数字来清理电话号码,从而删除其他所有内容。


推荐阅读