問題描述

我有一個案例,這是幾個自定義側邊欄中的很多小工具。我想知道是否有一個簡單的方式動態地改變每個小工具的標題。通常,小工具具有您可以手動設定或外掛本身設定的標題欄位。

我希望每個帖子將元欄位值新增到每個小工具標題中。

這個邏輯會是這樣的:

$dynamic_title = get_the_title();
// add a filter to change the widget titles per post value
//
// The widget title would be something like "Recent Posts for $dynamic_title"

我知道有一個 widget_title 過濾器,但是如何定位特定的小工具?

PS 。由於有許多小工具需要特定的標題,因此我無法使用常規的 register_sidebar 引數。

最佳解決方案

您可以使用 widget_display_callback(可以預見,在顯示視窗小工具之前觸發)) 。

add_filter('widget_display_callback','wptuts54095_widget_custom_title',10,3);

function wptuts54095_widget_custom_title($instance, $widget, $args){

    if ( is_single() ){
       //On a single post.
       $title = get_the_title();
       $instance['title'] = $instance['title'].' '.$title;
    }

    return $instance;
}

$widget 引數是您的視窗小工具類的物件,因此 $widget->id_base 將包含視窗小工具的 ID(如果定位到特定的視窗小工具類) 。

次佳解決方案

您可以使用自己的鉤子進行 widget_title 動作。您可以透過 $id_base 引數確定特定的小工具,該引數作為第三個引數傳遞給鉤子。它應該像這樣工作:

function myplugin_widget_title( $title, $instance, $id_base ) {
    if ( !is_single() ) {
        return $title;
    }

    $post_title = get_the_title();
    switch ( $id_base ) {
        case 'pages': return sprintf( '%s "%s"', $title, $post_title );
        case 'links': return sprintf( 'Links for "%s" post.', $post_title );
        // other widgets ...
        default: return $title;
    }
}
add_filter( 'widget_title', 'myplugin_widget_title', 10, 3 );

對於自定義小工具,您需要將此過濾器應用於小工具的標題才能回顯 (as shown the default widgets):

$title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Pages' ) : $instance['title'], $instance, $this->id_base);

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。