WooCommerce:如何按自定义字段对账户下载内容排序
实现WooCommerce账户下载内容按产品最后更新时间排序
要实现按产品最后更新时间优先排序下载内容,你需要先给woocommerce_customer_get_downloadable_products返回的下载数组注入产品的最后更新时间,再基于这个时间对数组排序,具体步骤如下:
1. 注入更新时间并排序下载数组
使用woocommerce_customer_get_downloadable_products钩子,遍历每个下载项,获取对应产品的最后更新时间并添加到数组中,再对数组进行排序:
add_filter( 'woocommerce_customer_get_downloadable_products', function( $downloads ) { // 遍历每个下载项,添加最后更新时间戳 foreach ( $downloads as &$download ) { $product_id = $download['product_id']; $product_changelog = get_post_meta( $product_id, 'product_changelog', true ); if ( $product_changelog ) { $latest_timestamp = 0; // 遍历更新日志,找出最新的时间戳 foreach ( $product_changelog as $log_entry ) { if ( isset( $log_entry['log_items']['1']['log_date'] ) ) { $timestamp = strtotime( $log_entry['log_items']['1']['log_date'] ); if ( $timestamp > $latest_timestamp ) { $latest_timestamp = $timestamp; } } } // 将最新时间戳添加到下载项数组 $download['last_updated_timestamp'] = $latest_timestamp; } else { // 如果没有更新日志,用产品发布时间作为 fallback $download['last_updated_timestamp'] = get_post_time( 'U', true, $product_id ); } } // 按最后更新时间戳降序排序(最新的在前) usort( $downloads, function( $a, $b ) { return $b['last_updated_timestamp'] - $a['last_updated_timestamp']; } ); return $downloads; } );
2. 优化原自定义列代码
你原来的自定义列代码存在逻辑漏洞:foreach循环会覆盖$timestamp变量,最终只输出最后一条日志的时间,而非产品的最新更新时间。可以调整为和上面逻辑一致的写法,确保显示的是最新更新时间:
// Callback For Account Downloads Last Updated add_action( 'woocommerce_account_downloads_column_download-updated', function( $data ) { $current_post_id = $data['product_id']; $product_changelog = get_post_meta( $current_post_id, 'product_changelog', true ); if ( $product_changelog ) { $latest_timestamp = 0; foreach ( $product_changelog as $log_entry ) { if ( isset( $log_entry['log_items']['1']['log_date'] ) ) { $timestamp = strtotime( $log_entry['log_items']['1']['log_date'] ); if ( $timestamp > $latest_timestamp ) { $latest_timestamp = $timestamp; } } } // 格式化显示时间 echo date( 'F j, Y', $latest_timestamp ); } else { // 没有更新日志时显示产品发布时间 echo date( 'F j, Y', get_post_time( 'U', true, $current_post_id ) ); } } );
说明
- 第一步的钩子负责在获取用户可下载产品列表时,给每个下载项附加最新更新时间戳,再通过
usort对数组进行降序排序,确保最新更新的产品排在最前面。 - 第二步优化后的代码确保自定义列显示的是产品的最新更新时间,同时增加了无更新日志时的 fallback 逻辑,避免空显示。
内容的提问来源于stack exchange,提问作者st0rm
相关产品推荐
相关产品推荐

