使用 Add_action 挂钩 Do-action

Hook Do-action with Add_action

我正在尝试调用使用 do_action 使用 add_action 创建的函数:

function.php的主题中:

function bleute_utbi_service_type()
{

 return "service";
}

add_action('utbi_service_type', 'bleute_utbi_service_type');

现在,我需要获取插件文件中函数的值:

// 'x' 插件文件:

function get_valor(){

$val = do_action('utbi_service_type');
echo "this is the valor:" . $val";

}

这种做法不行,$val return 'null'...为什么?

动作挂钩不 return 内容,老实说,如果您需要 action hook 到 return content,您很有可能做错了什么.

add_action() takes the identification of a function, in your case bleute_utbi_service_type(), and puts it into a list of functions to be called whenever anybody calls do_action().

$paramsdo_actionadd_action 一起使用,然后在 add_action 回调函数中设置 $value 或使用 filters到 return 内容。要了解 return 如何与 filters 一起使用,您可以参考这里:Wordpress: How to return value when use add_filter? or https://developer.wordpress.org/reference/functions/add_filter/

如果你想用 add_action 来做,你必须通过将参数传递给 add_action 来遵循这个引用 Reference

否则尝试使用这样的应用过滤器。

在function.php中添加以上代码:

function example_callback( $string ) {
    return $string;
}
add_filter( 'example_filter', 'example_callback', 10, 1 );

function get_valor(){
    $val = apply_filters( 'example_filter', 'filter me' );
    echo "this is the valor:". $val; 
}

并将以下代码添加到您要打印的位置:

get_valor();

希望对你有用:)