3

将 WooCoomerce 与WooCommerce 预订插件一起使用。在他们的API Reference中,列出了一个用于修改预订成本的过滤器:woocommerce_bookings_calculated_booking_cost。简而言之,以下是它在代码中的应用方式:

return apply_filters( 'woocommerce_bookings_calculated_booking_cost', $booking_cost, $product, $data );

现在,我添加了以下代码,尝试更改价格:

function foobar_price_changer( $booking_cost, $product, $data ) {
   return $booking_cost;
}

add_filter( 'woocommerce_bookings_calculated_booking_cost', 'foobar_price_changer' );

现在,当我使用该代码时,它会在我的日志中引发错误:

PHP Fatal error:  Uncaught ArgumentCountError: Too few arguments to function sbnb_modify_wc_bookings_price(), 1 passed in /mywppath/wp-includes/class-wp-hook.php on line 290 and exactly 3 expected in /mywppath/wp-content/themes/enfold-child/functions.php:155

据我阅读,3 个参数被传递给 add_filter 回调,但在我的例子中它只传递了一个。这里可能是什么问题?

4

2 回答 2

2

试试这个方法

function foobar_price_changer( $booking_cost, $product, $data ) {
   return $booking_cost;
}
add_filter( 'woocommerce_bookings_calculated_booking_cost', 'foobar_price_changer', 10, 3 ); // Where $priority is 10, $args is 3.
于 2020-02-19T13:45:52.267 回答
1

如果您在调用 add_filter 函数时没有指定 $accepted_args 或第四个参数,则默认情况下它只将一个参数传递给您的回调函数。因此,只要有多个参数要传递给回调函数,您就必须指定预期参数的数量。从 wp-includes/plugin.php:

* @global array $wp_filter A multidimensional array of all hooks and the callbacks hooked to them.
*
* @param string   $tag             The name of the filter to hook the $function_to_add callback to.
* @param callable $function_to_add The callback to be run when the filter is applied.
* @param int      $priority        Optional. Used to specify the order in which the functions
*                                  associated with a particular action are executed.
*                                  Lower numbers correspond with earlier execution,
*                                  and functions with the same priority are executed
*                                  in the order in which they were added to the action. Default 10.
* @param int      $accepted_args   Optional. The number of arguments the function accepts. Default 1.
* @return true
*/
function add_filter( $tag, $function_to_add, $priority = 10, $accepted_args = 1 ) {
   global $wp_filter;
   if ( ! isset( $wp_filter[ $tag ] ) ) {
       $wp_filter[ $tag ] = new WP_Hook();
   }
   $wp_filter[ $tag ]->add_filter( $tag, $function_to_add, $priority, $accepted_args );
   return true;
}
于 2020-09-08T13:36:54.310 回答