修改 Wordpress 功能以在标题的第一个单词周围放置跨度? [英] Revised Wordpress function to put a Span around the first word of the Title?

查看:27
本文介绍了修改 Wordpress 功能以在标题的第一个单词周围放置跨度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个函数,在 Wordpress 站点中每个帖子标题的第一个单词周围添加一个跨度",并找到了 这个极其相似的问题.当 H2 元素中有链接时,第二个答案中的函数可以正常工作.

I'm trying to use a function that adds a "span" around the first word of every post title in a Wordpress site, and found this extremely similar question. The function in the second answer works fine when there's a link inside the H2 element.

但是在我的网站中,我没有使用帖子标题作为链接,因此找到的解决方案不起作用.我试图想出一个新的 preg-replace 模式,以跳过链接部分的检测,但一直无法得到它.

But In my site, I'm not using the post title as a link, so the found solution doesn't work. I've tried to come up with a new preg-replace pattern, as to skip the detection of the link part, but haven't been able to get it.

基本上,我想要这个:

<h2><?php the_title(); ?></h2> or <h2>Converted post title</h2>

...变成这样:

<h2><span>Converted</span> post title</h2>

推荐答案

使用woodpress 挂钩和过滤器的最佳方法.这样你就可以不用额外的代码就可以使用 the_title() 函数了.

Best way to do that using woodpress hooks and filter. so that you can use the_title() function without additional code.

将此代码放入主题文件夹中的functions.php.仅此而已.

put this code into functions.php in your theme folder. that's all.

    function add_label_to_post_title( $title = '' ) {
       if(trim($title) != "")
       {
      $ARR_title = explode(" ", $title);
      
      if(sizeof($ARR_title) > 1 )
          {
             $first_word = "<span>".$ARR_title['0']."</span>";
             unset($ARR_title['0']);
             return $first_word. implode(" ", $ARR_title);
          }
          else
          {
              return "<span>{$title}</span>";
          }
       }
       return $title;
}
add_filter( 'the_title', 'add_label_to_post_title' );

这篇关于修改 Wordpress 功能以在标题的第一个单词周围放置跨度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆