2016-03-08 36 views

回答

0

這是利用原有WP的東西,基本上我認爲你是最簡單的格式要求的東西:

<?php 
$post_title = get_the_title(); 
$title_as_array = explode(' ', $post_title); 
$last_word = array_pop($title_as_array); 
$last_word_with_span = '<span class="whatever">' . $last_word . '</span>'; 
array_push($title_as_array,$last_word_with_span); 
$modified_title = implode(' ', $title_as_array); 
echo $modified_title; 
?> 

試用這在this PHP sandbox。你可以看到我用沙箱中的標題替換了一串字(「這是我的標題」) - 它應該像get_the_title()那樣工作。

這是按「執行代碼」後發生的情況,以防您沒有看到。 PS:爲了解釋,基本上這是:1)獲得標題作爲字符串,2)將其轉換爲數組,3)獲得數組中的最後一項,4)添加span html,5)回到標題數組的末尾,6)再次將數組轉換爲字符串,7)將其打印出來。

enter image description here

+0

所以我把整個PHP,而不是隻使用<?php the_title ... – user3550879

+0

是的,應該這樣做。如果您只需要在特定頁面上執行此操作,則可以使用它的條件標籤(https://codex.wordpress.org/Conditional_Tags)。 – tempranova

1

var sliced = $('h1').text().split(' '); 
 
var lastword = sliced.pop(); 
 
console.log(lastword)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<h1>Im the Last Word</h1>

嘗試這種方式..然後split()的H1使用pop()

+0

不知道這是工作或沒有它顯示了整個句子 – user3550879

+0

檢查您的控制檯將只顯示'word'使用Firefox和它的最後一個字 – guradio

+0

顯示句子 – user3550879

1

待辦事項拆你的文字,並通過採用分體式採取硬道理獲得最後一個字,並且必須替換爲文本在那附近。使用.html(function())像這樣:

var text = $('h1').text().split(' '); 
var lstWord = text.pop(); 
// find the h1 with above word 
$("h1:contains('" + lstWord + "')").html(function(i, old) { 
    // replace the old content(specified words) 
    // with span tag around that 
    return old.replace(lstWord, '<span class="myColor">'+lstWord+'</span>'); 
}); 

DEMO

+0

將這個替換整個< ?php the_title ...我不想將它應用於所有h1標籤。只是在帖子標題 – user3550879

+0

這個代碼將取代具有特定搜索詞的所有'h1'標籤。所以,你怎麼知道選擇哪個'h1',除非你知道它們只出現在這個例子的哪個位置:https://jsfiddle.net/norlihazmeyGhazali/ws34491x/ –

+0

還是有點困惑,但是如果我把它放在旁邊PHP和不在< head >它只適用於職位標題? – user3550879

相關問題