2016-08-22 82 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