2016-08-22 51 views
0

我想更改get_header_image_tag函數的輸出以輸出我想要的確切HTML。我也希望能夠將數據添加到輸出如新srcset還沒有被覆蓋......WordPress - 覆蓋/過濾get_header_image_tag

我曾嘗試使用apply_filters get_header_image_tag對其進行測試,但不能得到它的工作:

apply_filters('get_header_image_tag', "<img src>", get_custom_header(), ['url' => 'test']); 
echo get_header_image_tag(); 

我相當相信我對apply_filters工作方式的理解可能是那裏的問題......我一直在閱讀它,但我無法理解這些參數。我在網上找到的大多數例子都只使用一個鉤子和一個值。

我的理解是,我想通過使用get_custom_header()中的數據並用'test'替換URL屬性來輸出<img src=url>

但是,輸出的是默認的get_header_image_tag。我也試過直接呼應apply_filters:

echo apply_filters('get_header_image_tag', "<img src>", get_custom_header(), ['url' => 'test']); 

不過,只有<img src>輸出...

回答

1

你是完全正確的,這是你如何使用WordPress的過濾器,是理解問題:)

您在使用apply_filters()時正在應用濾鏡。要將您自己的過濾器添加到get_header_image_tag掛鉤,您必須使用add_filter()。下面是關於如何添加過濾器應該像一個例子:

// define the get_header_image_tag callback 
function filter_get_header_image_tag($html, $header, $attr) { 
    // make filter magic happen here... 
    return $html; 
}; 

// add the filter 
add_filter('get_header_image_tag', 'filter_get_header_image_tag', 10, 3); 

下面是如何控制get_header_image_tag全力輸出的例子:

function header_image_markup($html, $header, $attr) { 
    return '<figure><img src="'.$attr['src'].'" width="'.$attr['width'].'" height="'.$attr['height'].'" alt="'.$attr['alt'].'" srcset="'.$attr['srcset'].'" sizes="'.$attr['sizes'].'"></figure>'; 
} 

add_filter('get_header_image_tag', 'header_image_markup', 20, 3); 

但是,什麼版本的WP是你使用?我很確定srcset在get_header_image_tag()中被支持,就像我剛纔使用它時出現的那樣。

+0

謝謝,我昨天想到了關於add_filter的事情...然後幾個小時後,它實際上使用默認參數覆蓋了輸出xD我總是使用WP的最後一個版本,但是,當支持srcset時,我們要控制自己的輸出:) 我打算讀更多關於add_filter,apply_filter,add_action和do_action;) – Dacramash

+0

@Dacramash哈哈,我知道這種感覺:)動作和過濾器都很棒! [WordPress的有2000多個鉤子](https://developer.wordpress.org/reference/hooks/),所以有很多玩:) – lassemt