我正在尝试在POST TITLE中找到任何帖子TAGS,并preg_replace
与span
包围的标记匹配,以向其添加css(粗体)。最终结果应该是帖子标题,其中任何标签都以粗体显示。
<h2 class="entry-title">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink to <?php the_title(); ?>">
<?php
$titlename = the_title();
$tags = array(just_tags());
foreach($tags as $tag) {
$displaytitle = preg_replace("$tag", "<span class=\"larger\">$tag</span>", $titlename);
}
echo $displaytitle;
?>
</a>
</h2>
正如您在代码中看到的,我修改了一些函数以尝试仅获取代码,而不是$before
和$after
。
function get_just_the_tag_list() {
return get_the_term_list('post_tag');
}
function just_tags() {
echo get_just_the_tag_list();
}
答案 0 :(得分:1)
您的preg_replace
正在寻找$titlename
中的文字“$ tag”。将其从引号中取出,或用大括号"{$tag}"
包裹它!
get_the_terms_list
返回HTML格式的术语列表。您想要使用get_the_terms
,并且它会自动作为数组返回,因此应该像这样定义$tags
(假设它在循环中并且$post
是准确的:
$tags = get_the_terms($post->ID, 'post-tags');
<h2 class="entry-title">
<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permalink to <?php the_title(); ?>">
<?php
$titlename = get_the_title();
$tags = get_the_terms($post->ID, 'post_tag');
foreach($tags as $tag) {
$titlename = str_replace($tag->name, '<span class="larger">'.$tag->name.'</span>', $titlename);
}
echo $titlename;
?>
</a>
</h2>
这意味着您的$displaytitle
正在为每个$tag
完全重写,如果在帖子标题中找不到最后$tag
,则不会发生任何变化。
答案 1 :(得分:1)
你不能做这样的事吗?
$titlename = the_title();
$tags = get_the_terms($post->ID, 'post_tag');
foreach($tags as $tag) {
$displaytitle = str_replace($tag->name, "<span class=\"larger\">$tag</span>", $titlename);
}
您不需要使用正则表达式,因为您想要替换整个标记。 1}}功能不再需要了。
答案 2 :(得分:0)
你应该真正研究Wordpress过滤器。直接在the_title()上有一个过滤器,它允许您执行此功能。
apply_filters('the_title','my_filter')
function my_filter($title)
{
//do what you want and
return $title; //when finished altering.
}
如果你想保持自己的方式
get_the_title()
$titlename = get_the_title();//inside the loop
or
global $post;
$titlename = get_the_title($post->ID);//outside the loop
加上crowjonah的回答,删除$ tag周围的引号,尽管你可能需要把它preg_replace("/" . $tag->name . "/", '<span class="larger">'.$tag->name.'</span>', $titlename );
或Benjamin Paap的str_replace
str_replace($tag->name, '<span class="larger">'.$tag->name.'</span>', $titlename );