2010-10-28 72 views
1

我試圖創建一個函數,當它的保存(the_content)時對文章內容進行文本替換。如何使用str_ireplace()在發佈/保存例程期間過濾帖子內容?

存根函數在下面,但是如何獲得對發佈內容的引用,然後將過濾的內容返回到「publish_post」例程?

但是,我的替換要麼不工作和/或不傳遞更新post_content發佈功能。值不會被替換。

function my_function() { 
    global $post; 
    $the_content = $post->post_content; 
    $text = " test "; 
    $post->post_content = str_ireplace($text, '<b>'.$text.'</b>', $the_content ); 
    return $post->post_content; 
    } 
add_action('publish_post', 'my_function'); 

回答

0

可能更容易做這樣的事情:

function my_function($post) { 
    $content = str_ireplace(" test ", '<b>'.$text.'</b>', $post->content); 

    return $content; 
} 

較少關注的是函數的內部,但這個想法是,你傳遞對象在()函數然後調用直接而不是全球化價值。這應該是更直接的方式。

+0

感謝小屋。看起來不錯,但是當我測試它時,點擊帖子編輯器上的「更新」後內容保持不變。我想用粗體替換替換「測試」一詞的所有實例... – 2010-10-28 15:29:54

0

這裏傳遞的變量是$ id。這應該工作:

function my_function($id) { 
    $the_post = get_post($id); 
    $content = str_ireplace(" test ", '<b>'.$text.'</b>', $the_post->post_content); 

    return $content; 
} 
add_action('publish_post', 'my_function'); 
+0

不會更改帖子內容。你在哪裏傳遞$ id?順便說一句,像名字。我在bham,@ – 2010-10-28 17:59:15

+0

@Scott,很有趣。在我的代碼中,我想覆蓋所有的基礎,所以我使用了三個鉤子:edit_post,save_post和publish_post。搜索WordPress(v。3.0。1)源我不會立即看到do_action('publish_post')的調用。也許試試save_post呢?do_action方法WordPress使用do_action('save_post',$ post_ID,$ post),這是post ID和post對象的傳遞位置。 – bhamrick 2010-10-29 15:15:38

5

當你提到the_content,你是否引用模板標記或過濾器鉤?

the_content作爲過濾器掛鉤只能在數據庫讀取期間發佈內容,而不是寫入。在保存到數據庫之前修改發佈內容時使用的過濾器是content_save_pre

代碼示例

在你的插件或主題的functions.php文件,添加功能,採用$content作爲參數。以您希望的方式修改內容,並確保返回$content

然後使用add_filter('filter_name', 'function_name')在WordPress中遇到過濾器掛鉤時運行該函數。

function add_myself($content){ 
return $content." myself"; 
} 
add_filter('content_save_pre','add_myself'); 

如果我寫了一個帖子,其中包括:

「爲了帖子的最後,我想補充」

時保存到數據庫中,並在網站上顯示,它會顯示爲:

「到帖子末尾,我喜歡添加自己」。

你的榜樣過濾器可能被修改爲如下所示:

function my_function($content) { 
    $text = " test "; 
    return str_ireplace($text, '<b>'.$text.'</b>', $content ); 
} 
add_filter('content_save_pre','my_function'); 
相關問題