javascript - 在 WordPress 中将动态内容标题拆分为两种颜色
问题描述
我在 WP 中设计的网站有一个标题的运行主题,标题的前半部分是一种颜色,后半部分带有重音,使用静态标题很容易使用 span 标签,即
HTML:
<h1>This Is <span>My Headline</span></h1>
CSS:
h1 {color:#1f7b76;}
span {color:#75b482}
但是对于动态的标题,我不确定如何在 WordPress 框架内完成这项工作。
我查看了这个答案,但我认为这不适用于 WordPress 所需的标题颜色效果
解决方案
我想出了以下似乎可以满足您的需求:
$title = "My absolutely amazing WordPress post!";
$title_array = explode( " ", $title );
function addSpanToTitle( $t ) {
$word_count = count( $t );
if ( $word_count % 2 == 0 ) {
$half = $word_count / 2;
} else {
$half = ceil( $word_count / 2 );
}
$result = "";
for ( $i = 0; $i < $word_count; $i++ ) {
if ( $i < $half ) {
$result .= $t[ $i ] . " ";
} elseif ( $i == $half ) {
$result .= "<span>" . $t[ $i ] . " ";
} elseif ( $i > $half ) {
if ( $i == $word_count - 1 ) {
$result .= $t[ $i ] . "</span>";
} else {
$result .= $t[ $i ] . " ";
}
}
}
return $result;
}
echo "<h1>" . addSpanToTitle( $title_array ) . "</h1>";
要在 WordPress 中使用它,您可以在主题中定义函数functions.php
并在模板中执行以下操作:
<?php $the_title = explode( " ", get_the_title() ); ?>
<h1><?= addSpanToTitle( $the_title ); ?></h1>
本质上,这个函数的作用是接收一个数组——你的标题已经被分解了——然后计算出中间点,然后在<span>
中间点的单词之前添加一个开头(四舍五入)——如果你的标题是 6 个单词长,最后 3 个单词将在 span 内,如果您的标题长度为 5 个单词,则 span 将包含最后两个单词。
在标题的末尾,span 是关闭的。这是从函数作为字符串返回的。该函数就是您从该脚本中所需要的,其余代码已添加,因此您可以复制和粘贴并查看它如何处理各种字符串。
这绝对可以改进并写得更简洁,但这似乎可以满足您的需求,尽管并不完美。
这是将标题作为字符串的函数的修订版本:
function addSpan( $title ) {
$title = explode( " ", $title );
$half = count( $title ) % 2 == 0 ? count( $title ) / 2 : ceil(count( $title ) / 2 );
$result = "";
for ( $i = 0; $i < count( $title ); $i++ ) {
if ( $i == $half ) {
$result .= "<span>" . $title[ $i ] . " ";
} elseif ( $i == count( $title ) - 1 ) {
$result .= $title[ $i ] . "</span>";
} else {
$result .= $title[ $i ] . " ";
}
}
return $result;
}
用法:
<h1><?= addSpan( get_the_title() ); ?></h1>
推荐阅读
- css - React Bootstrap NavBar Container,将宽度设置为自动
- shell - IFTTT & Raspberry pi:从终端分配值到 IFTTT Web 请求
- android - 我在适配器中得到空指针异常
- java - 如何将 Drive API 集成到我的 Java 应用程序(在哪个文件中?)
- javascript - Ng Date Picker 如何格式化为不同的输出而不是 ISO-8601
- java - 在 Android 模拟器中从本地 FTP 服务器下载时出现错误“227 进入被动模式”/“连接被拒绝”
- microsoft-graph-api - 将项目上传到个人 OneDrive 共享文件夹
- javascript - 将数组转换为嵌套对象
- c++ - lambda 尾随返回类型 auto 的用途是什么?
- java - Jelly 中的 ${it} 变量是如何设置的