2012-12-07 43 views
0

我試圖找到POST帖子中的任何帖子標籤,並且preg_replace與被span包圍的標籤匹配,以向其添加css(粗體)。最終結果應該是帶有粗體標記的帖子標題。如何在WordPress的標題中預先放置標籤?

 <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

'preg_replace'中的'$ tag'變量不應該用引號引起來。 – crowjonah

+0

對......我忘了改回來看看是否有一些奇怪的原因,這可能會有所作爲,但事實並非如此。 – NotJay

+0

你正在爲每個'$ tag'重寫'$ displaytitle',所以如果最後一個標籤不匹配,什麼都不會改變。檢查我更新的答案。 – crowjonah

回答

1

preg_replace正在尋找$titlename文本 「$標籤」。把它從引號中拿出來,或者用大括號"{$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沒有在文章標題中發現,什麼都不會改變。

+0

我已刪除問題下方評論中提到的引號。仍然沒有在帖子標題的標籤周圍找到任何跨度。 – NotJay

+0

當我查看源代碼時,我最終在標題末尾添加了空跨度標記...沒有標記(加上它不應該在末尾) – NotJay

+0

有人在我的答案中編輯了'preg_replace' ... – crowjonah

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的回答,除去約$標籤的報價,雖然你可能需要使它preg_replace("/" . $tag->name . "/", '<span class="larger">'.$tag->name.'</span>', $titlename );

或者本傑明Paap's str_replace

str_replace($tag->name, '<span class="larger">'.$tag->name.'</span>', $titlename ); 
+0

對,在str_replace之前,我得到了標題中每個字母之間的跨度 – NotJay

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); 
} 

您不需要使用正則表達式,因爲您要替換整個標記。 just_tags函數不再需要。

相關問題