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

Wordpress 重新生成旧订单的下载权限,wordpress,woocommerce,Wordpress,Woocommerce,我正试图通过脚本向所有以前的订单添加一些下载权限,以便成批执行这些操作。除了一件事之外,这个剧本似乎很好用。这是剧本 function update_download_permissions(){ $orders = get_posts( array( 'post_type' => 'shop_order', 'post_status' => 'wc-completed', 'posts_per_page' => -1 ) );

我正试图通过脚本向所有以前的订单添加一些下载权限,以便成批执行这些操作。除了一件事之外,这个剧本似乎很好用。这是剧本

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_可下载_产品_权限函数在wp_可下载_产品_权限表中产生重复条目

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

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


干杯

我在翻阅WooCommerce的一些源代码后遇到了您的问题,当时我正在尝试向现有订单添加一个项目,然后重新生成权限

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

第二个
force
参数(文档不完整)与一个布尔标志相关,该标志指示
wc\u downloadable\u product\u permissions()
以前是否运行过。在函数末尾,通过set_download_permissions_grated方法将布尔值设置为true。如果
force
为true,它将忽略布尔值。如果
force
为false,且布尔值为true,则函数将在接近开始时返回

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


谢谢你。我应该在我的原始问题中添加,在运行代码之前,数据库中没有下载权限。我首先删除了所有权限(当然这是一个沙盒站点;))。因此,它不是再添加一行,实际上是添加了两个新行。在这种情况下,我唯一的猜测是,
wc\u downloadable\u product\u permissions()
运行了两次;这仍然应该有效,因为它将在第二次运行时删除并重新添加。如果不是这样,我会检查其中一个产品上$product->get\u downloads()的输出(WC\u product方法,您可以使用WC\u get\u product来获取实例)。源代码正在其返回的每个数组项上运行
wc\u downloadable\u file\u permission()
(注意:单数)。另请参见我如何处理此问题。
/**
 * 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 );

}