每个分类术语的平均 post 年龄(以天为单位)

Average post age in days per taxonomy term

我正在为目录网站构建一些统计信息,但我无法计算分配给特定列表类型的列表的平均年龄。

我想出了按 ID 计算上市时间(以天为单位)的方法:

$today = date( 'Y-m-d' );
$listing_date = get_the_date( 'Y-m-d', $id );
$diff = strtotime( $today ) - strtotime( $listing_date );
$age = round( $diff / 86400 );

我想出了如何通过术语 ID 提取分配给特定列表类型的列表:

$args = array(
    'posts_per_page' => -1,
    'fields' => 'ids',
    'post_type' => 'listing',
    'post_status' => 'publish',
    'tax_query' => array(
        array(
        'taxonomy' => 'listing-type',
        'field' => 'id',
        'terms' => $id
        )
    )
);
$ids = get_posts( $args );

这为我提供了一组分配给特定列表类型的所有列表的 ID。 现在我需要计算我检索 ID 的所有列表的总年龄(以天为单位)。

我想 $cnt = count( $ids ); 获取检索到的列表 (ID) 的总数,但我无法计算这些列表的总年龄(以天为单位)。

使用 foreach 循环:

<?php

// Your function to get the diff
function get_diff($id) {
   $today = date( 'Y-m-d' );
   $listing_date = get_the_date( 'Y-m-d', $id );
   $diff = strtotime( $today ) - strtotime( $listing_date );
   $age = round( $diff / 86400 );

   return $age;
}


// We want to store all the diff
$diffs = [];

foreach($ids as $id) {
   $diffs[] = get_diff($id);
}

// Get the average | We filter to remove empty values
$diffs = array_filter($diffs);
if(count($diffs)) {
    echo $average = array_sum($diffs)/count($diffs);
}