【问题标题】:Regenerating WooCommerce Download Permissions on older orders为旧订单重新生成 WooCommerce 下载权限
【发布时间】:2018-11-30 08:01:24
【问题描述】:

我正在尝试通过脚本为所有以前的订单添加一些下载权限以批量执行。该脚本似乎可以正常工作,期待一件事。这是脚本……

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(默认值),但这导致没有创建权限。

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

干杯!

【问题讨论】:

标签: wordpress woocommerce


【解决方案1】:

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

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

第二个force 参数(文档很少)与一个布尔标志相关,该标志指示wc_downloadable_product_permissions() 之前是否运行过。在函数结束时通过 set_download_permissions_granted 方法将布尔值设置为 true。如果force 为真,它将忽略布尔值。如果force 为假,而布尔值为真,则函数将在开始附近返回。

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

/**
 * 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 );

}

【讨论】:

  • 谢谢。在我运行代码之前,我应该在我原来的问题中添加数据库中没有下载权限。我首先删除了所有权限(当然这是一个沙盒站点;))。所以它不是再添加一个,实际上是添加了两个新行。
  • 在这种情况下,我唯一的猜测是wc_downloadable_product_permissions() 运行了两次;这仍然应该有效,因为它会在第二次运行时删除并重新添加。如果不是这种情况,我会检查其中一个产品的 $product->get_downloads() 的输出(WC_Product 方法,您可以使用 wc_get_product 获取实例)。源在其返回的每个数组项上运行 wc_downloadable_file_permission()(注意:单数)。
猜你喜欢
  • 1970-01-01
  • 2016-07-24
  • 2021-11-21
  • 1970-01-01
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多