2013-12-19 16 views
1

我創建了一個過濾器,修改post_title(),但我遇到的問題是,它正在修改the_title()的每個實例。我用in_the_loop()函數解決了大部分問題,但是任何在循環中有「next post」「previous post」導航鏈接的主題仍然應用了過濾器(可以這麼理解)。我如何才能將過濾器應用於當前帖子的the_title()?你怎麼add_filter只有一個實例的the_title()

function xyz_the_title($the_title) { 

    if(!in_the_loop()) 
     return $the_title; 

    $location = get_post_meta(get_the_ID(), 'location', true); 

    $the_title .= ' - ' . $location; 

    return $the_title; 

} 

add_filter('the_title', 'xyz_the_title'); 
+0

我以爲你只是試圖影響「the_title」,正確的最頂端實例? –

+0

這是正確的。如果你把這個網頁作爲一個例子http://twentythirteendemo.wordpress.com/2013/02/11/popular-science/,文本「大衆科學」是我想改變的。我的代碼也正在改變我不想改變的底部附近的「怪物引擎」文本。 – CCCP

+0

如果是這樣,使用過濾器不是一個正確的方法。您應該在輸出標題的地方自定義您的主題。 – s976

回答

0

做到與jQuery

像這樣的東西應該做的伎倆:

$(document).ready(function() { 
    $('#entry-header').text(function(i, oldText) { 
     return oldText === 'Popular Science' ? 'New word' : oldText; 
    }); 
}); 

這隻有當它是科普替換內容。請參閱jQuery API中的文本。

+0

我需要一個wordpress站點的代碼,大約有5,000個帖子。我不認爲這個解決方案是可行的。 – CCCP

0

而不是過濾the_title你可以編輯你的模板文件,而是將位置附加到你返回的the_title()。

  echo "<h1>" . get_the_title() . " - " . $location . "</h1>"; 
+0

這不起作用,因爲它會要求任何使用我的插件的人都必須爲他們正在使用的主題編輯適當的模板文件。 – CCCP

1

啊,不知道是爲了一個插件。在這種情況下,我認爲你應該可以使用if_filter。這將檢查過濾器是否在相關頁面上運行了x次。因此,我們檢查它是否在頁面上運行過一次,如果是,它將不會再運行。另外,我假設你只想讓它在單個帖子頁面上運行。這是未經測試的。

function xyz_the_title($the_title) { 

    if(is_single() AND did_filter('the_title') === 1) { 

     if(!in_the_loop()) 
      return $the_title; 

     $location = get_post_meta(get_the_ID(), 'location', true); 
     $the_title .= ' - ' . $location; 
     return $the_title; 
    } 
} 
add_filter('the_title', 'xyz_the_title'); 
0

遇到類似的情況,並希望這個線程能救我......

不管怎麼說,這是我能夠做到迄今在

add_filter('the_title', function($title, $id){ 
    /** 
    * don't run in the backend 
    */ 
    if(is_admin()) { 
     return $title; 
    } 


    /** 
    * invalid values received 
    */ 
    if(empty($title) || $id < 1){ 
     return $title; 
    } 


    global $post; 
    if (! $post instanceof WP_Post){ 
     return $title; 
    } 


    /** 
    * PREVENTATIVE MEASURE... 
    * only apply the filter to the current page's title, 
    * and not to the other title's on the current page 
    */ 
    global $wp_query; 
    if($id !== $wp_query->queried_object_id){ 
     return $title; 
    } 

    /** 
    * Don't run this filter if wp_head calls it 
    */ 
    if(doing_action('wp_head')){ 
     return $title; 
    } 

    return 'MODIFIED - '.$title; 
}); 

這裏有缺點:

  1. 如果你有相同的職位b eing顯示當前頁面上的其他地方,它會修改文章標題,以及

目前想在看看調用堆棧,以檢測如果呼叫從主題來了...

,但我會建議你找另一個解決方案蕾...

相關問題