【问题标题】:WordPress - Overwriting/Filtering get_header_image_tagWordPress - 覆盖/过滤 get_header_image_tag
【发布时间】:2016-08-23 06:43:59
【问题描述】:

我想更改 get_header_image_tag 函数的输出以输出我想要的确切 HTML。我还希望能够将数据添加到输出中,例如尚未涵盖的新 srcset...

我尝试使用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 工作原理的理解可能是那里的问题......我一直在阅读它,但我无法理解这些参数。我在网上找到的大多数示例只使用了一个钩子和一个值。

按照我的理解,我希望输出为&lt;img src=url&gt;,方法是使用get_custom_header() 中的数据并将URL 属性替换为'test'。

但是,输出的是默认的 get_header_image_tag。我也尝试直接回显 apply_filters:

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

然后,只输出&lt;img src&gt;...

【问题讨论】:

    标签: php wordpress wordpress-theming hook


    【解决方案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?我很确定 get_header_image_tag() 支持 srcset,就像我刚才使用它时出现的那样。

    【讨论】:

    • 谢谢,我昨天发现了关于 add_filter 的事情......然后几个小时后,它实际上是使用默认参数覆盖输出 xD 我总是使用最后一个版本的 WP 但是,虽然支持 srcset,但我们希望自己控制输出 :) 我计划阅读更多关于 add_filter、apply_filter、add_action 和 do_action 的内容;)
    • @Dacramash 哈哈,我知道那种感觉 :) 动作和过滤器很棒! Wordpress has 2000+ hooks 所以有很多东西可以玩:)
    猜你喜欢
    • 2018-02-19
    • 2019-06-02
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多