我正在尝试通过脚本向所有以前的订单添加一些下载权限以批量执行它们。除了一件事之外,该脚本似乎运行良好。这是脚本...
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(默认值),但这导致没有创建任何权限。
有人知道为什么要设置重复下载权限吗?
干杯!
最佳答案
我在深入研究一些 WooCommerce 源代码并尝试将项目添加到现有订单然后重新生成权限后遇到了您的问题。
wc_downloadable_product_permissions()
将创建重复权限条目的原因是它不检查任何现有权限。它只是在订单中的每个项目的权限表中插入另一个条目,这不好,因为这将在管理员和用户帐户前端中显示为另一个下载。
第二个 force
参数(记录很少)与一个 bool 标志相关,该标志指示 wc_downloadable_product_permissions()
之前是否运行过。在函数末尾通过 set_download_permissions_granted 方法将 bool 值设置为 true。如果 force
为 true,它将忽略 bool 值。如果 force
为 false,且 bool 值为 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 );
}
关于wordpress - 重新生成旧订单的 WooCommerce 下载权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53553478/