wordpress-在功能中调用add_filter

发布于 2025-02-10 06:44:10 字数 1016 浏览 1 评论 0原文

我从模板中调用函数(函数放置在them function.php中)。此功能应调用add_filter body_class。打印“尝试调用添加过滤器”,但add_filter无法正常工作。当我在功能之外使用add_filter时,它将起作用。这两种方式都无法正常工作:/

方式1

add_action('test_callback_add_no_hero_class', 'test_callback_add_no_hero_class_funct');
function test_callback_add_no_hero_class_funct() {
    echo 'Try to call add filter';
    add_filter( 'body_class', function( $classes ) {
        return array_merge( $classes, array( 'pxlr-site-no-hero' ) );
    } );
}

//do_action('test_callback_add_no_hero_class'); // call from my template

路2

add_action('test_callback_add_no_hero_class', 'test_callback_add_no_hero_class_funct');
function test_callback_add_no_hero_class_funct() {
    echo 'Try to call add filter';
    add_filter( 'body_class', 'pxlr_nohero_custom_class' );
}

function pxlr_nohero_custom_class( $classes ) {
    $classes[] = 'pxlr-site-no-hero';
    return $classes;
}

//do_action('test_callback_add_no_hero_class'); // call from my template

I call a function (function is placed in theme functions.php) from my template. This function should call add_filter body_class. "Try to call add filter" is printed but add_filter will not work. When I use the add_filter outside the function it will work. Both ways here are not working :/

Way 1

add_action('test_callback_add_no_hero_class', 'test_callback_add_no_hero_class_funct');
function test_callback_add_no_hero_class_funct() {
    echo 'Try to call add filter';
    add_filter( 'body_class', function( $classes ) {
        return array_merge( $classes, array( 'pxlr-site-no-hero' ) );
    } );
}

//do_action('test_callback_add_no_hero_class'); // call from my template

Way 2

add_action('test_callback_add_no_hero_class', 'test_callback_add_no_hero_class_funct');
function test_callback_add_no_hero_class_funct() {
    echo 'Try to call add filter';
    add_filter( 'body_class', 'pxlr_nohero_custom_class' );
}

function pxlr_nohero_custom_class( $classes ) {
    $classes[] = 'pxlr-site-no-hero';
    return $classes;
}

//do_action('test_callback_add_no_hero_class'); // call from my template

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靖瑶 2025-02-17 06:44:10

摘要代码在路1中没有问题。由于操作调用,过滤器无法正常工作。 test_callback_add_no_hero_class操作应在

there is no problem with the snippet code in way 1. The filter isn't working because of the action call. test_callback_add_no_hero_class action, should run before the apply_filters.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文