php - 如何将这些自定义字段组合为 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; ?>
解决方案
你可以做这样的事情。您只需根据需要向链接数组添加任意数量的条目。这样你就可以避免重复很多代码。
$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 行旨在通过仅允许其中的数字来清理电话号码,从而删除其他所有内容。
推荐阅读
- java - mvn install 时出现编译错误“-source 1.5 中不支持菱形运算符”
- firebase - Nuxt SPA Firebase 托管:从 __/firebase/init.js 文件中读取配置
- r - r data.table - tstrsplit 函数 - 当列以匹配字符串开头时,第一列为空白
- swift - NSWorkspace.OpenConfiguration() 不工作?- 斯威夫特
- python - 如何使用 discord.py 制作类似于 KDBot 的 TTS 机器人?
- reactjs - 如何全屏显示地图并以 react-simple-maps 为中心
- wordpress - 中心元素中带有图标的文本路径
- javascript - Google Places API 返回错误:使用 Axios 时出现网络错误
- vb.net - 尝试在子例程中设置一维数组时出现 VB.NET NullReferenceException
- github - 通过 url 将标签添加到 GitHub PR