首页 > 解决方案 > 在 WordPress 中将动态内容标题拆分为两种颜色

问题描述

我在 WP 中设计的网站有一个标题的运行主题,标题的前半部分是一种颜色,后半部分带有重音,使用静态标题很容易使用 span 标签,即

HTML:

<h1>This Is <span>My Headline</span></h1>

CSS:

h1 {color:#1f7b76;}
span {color:#75b482}

但是对于动态的标题,我不确定如何在 WordPress 框架内完成这项工作。

我查看了这个答案,但我认为这不适用于 WordPress 所需的标题颜色效果

标签: javascriptcsswordpressdynamic

解决方案


我想出了以下似乎可以满足您的需求:

$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>

推荐阅读