自定义和添加 woocommerce 模板数据

Jam*_*mie 5 php wordpress hook templates woocommerce

我在自定义 WordPress 主题中的 woocommerce 模板时遇到一些问题。我想在我的模板中添加额外的数据作为变量。

我想在仪表板/我的帐户页面上显示活动订单。我想通过按顺序将数据变量传递到模板以便能够调用来实现此目的,就像在模板中完成的那样orders.php

我知道我可以覆盖我的主题中的 ,然后在仪表板或我的帐户的函数wc-template-functions.php中添加数据。wc_get_templates但是,我不想这样做。

我尝试过创建一个钩子,例如:

函数.php

function wc_fr_add_orders_to_account( $fr_account_orders, $current_page ) {
  global $fr_account_orders;
  $current_page = empty( $current_page ) ? 1 : absint( $current_page );

  $customer_orders = wc_get_orders( apply_filters( 'woocommerce_my_account_my_orders_query', 
    array( 
      'customer' => get_current_user_id(), 
      'page' => $current_page, 
      'paginate' => true,
      'status' => array( 'wc-pending' )
      ) ) );

  $fr_account_orders = array(
    'current_page' => absint( $current_page ),
    'customer_orders' => $customer_orders,
    'has_orders' => 0 < $customer_orders->total
  );

  return $fr_account_orders;
}
add_action( 'woocommerce_account_content', 'wc_fr_add_orders_to_account' );
Run Code Online (Sandbox Code Playgroud)

/theme-directory/woocommerce/templates/myaccount/dashboard.php(也在 my-account.php 中尝试过)

do_action( 'woocommerce_account_dashboard', $fr_account_orders);
var_dump($fr_account_orders);
Run Code Online (Sandbox Code Playgroud)

$fr_account_orders返回 null。但是,如果我var_dump在钩子函数中使用数组,它就会返回数据。任何帮助表示赞赏。

小智 1

那里很容易。如果你想返回变量,那不是这样做的方法。你应该apply_filters这样使用:

function wc_fr_add_orders_to_account() {
    /* your function */

    return $fr_account_orders;
}
add_filter( 'woocommerce_account_dashboard', 'wc_fr_add_orders_to_account' );
Run Code Online (Sandbox Code Playgroud)

并在你的模板中..

$my_var = apply_filters( 'woocommerce_account_dashboard', $fr_account_orders );
var_dump( $my_var );
Run Code Online (Sandbox Code Playgroud)

现在,如果您想发送一些变量,请像这样:

function wc_fr_add_orders_to_account( $var1, $var2 ) {
    /* your function */

    return $fr_account_orders;
}
add_filter( 'woocommerce_account_dashboard', 'wc_fr_add_orders_to_account', 10, 3 );
Run Code Online (Sandbox Code Playgroud)

并再次在您的模板中..

$my_var = apply_filters( 'woocommerce_account_dashboard', $fr_account_orders, $var1, $var2 );
var_dump( $my_var );
Run Code Online (Sandbox Code Playgroud)

apply_filters在这里阅读更多信息https://developer.wordpress.org/reference/functions/apply_filters/还有一件事,尽量不要更改模板,而是使用模板中的add_action挂钩do_action以获得更好的兼容性。谢谢!