重新生成旧订单的 WooCommerce 下载权限

2023-12-31

我正在尝试通过脚本向所有以前的订单添加一些下载权限以批量执行它们。除了一件事之外,该脚本似乎运行良好。这是脚本...

function update_download_permissions(){

  $orders = get_posts( array(
    'post_type'      => 'shop_order',
    'post_status'    => 'wc-completed',
    'posts_per_page' => -1
  ) );

  foreach ( $orders as $order ) {
    wc_downloadable_product_permissions( $order->ID, true );
  }

}

问题是 wc_downloadable_product_permissions 函数在 wp_woocommerce_downloadable_product_permissions 表中生成重复条目。

我尝试将第二个参数设置为 false(默认值),但这导致没有创建任何权限。

有人知道为什么要设置重复下载权限吗?

Cheers!


我在挖掘一些 WooCommerce 源代码并尝试将项目添加到现有订单然后重新生成权限后遇到了您的问题。

原因wc_downloadable_product_permissions()会创建重复的权限条目是因为它不检查任何现有权限。它只是在订单中的每个项目的权限表中插入另一个条目,这不好,因为这将在管理员和用户帐户前端中显示为另一个下载。

第二force参数(记录很少)与一个布尔标志相关,该标志指示是否wc_downloadable_product_permissions()之前已经跑过。在函数末尾通过 set_download_permissions_granted 方法将布尔值设置为 true。如果force为 true 时,它​​将忽略布尔值。如果force为 false,且布尔值为 true,函数将在开始处附近返回。

我创建了这个函数,它使用与管理订单操作“重新生成下载权限”所使用的函数相同的函数:

/**
 * Regenerate the WooCommerce download permissions for an order
 * @param  Integer $order_id
 */
function regen_woo_downloadable_product_permissions( $order_id ){

    // Remove all existing download permissions for this order.
    // This uses the same code as the "regenerate download permissions" action in the WP admin (https://github.com/woocommerce/woocommerce/blob/3.5.2/includes/admin/meta-boxes/class-wc-meta-box-order-actions.php#L129-L131)
    // An instance of the download's Data Store (WC_Customer_Download_Data_Store) is created and
    // uses its method to delete a download permission from the database by order ID.
    $data_store = WC_Data_Store::load( 'customer-download' );
    $data_store->delete_by_order_id( $order_id );

    // Run WooCommerce's built in function to create the permissions for an order (https://docs.woocommerce.com/wc-apidocs/function-wc_downloadable_product_permissions.html)
    // Setting the second "force" argument to true makes sure that this ignores the fact that permissions
    // have already been generated on the order.
    wc_downloadable_product_permissions( $order_id, true );

}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重新生成旧订单的 WooCommerce 下载权限 的相关文章

随机推荐