我需要一个函数来将保存的POST_DATE或POST_DATE_GMT更改为WordPress中的相对时间

时间:2011-11-27 作者:Ravi Soni

我正在开发一个插件,希望将默认发布日期更改为“一分钟前发布”或“一小时前发布”或“一个月前发布”。

2 个回复
最合适的回答,由SO网友:kaiser 整理而成

直接从我的框架human_time_diff() 涉及缓存。

/**
 * Time since an entry was posted
 * 
 * Adapted from binary bonsai
 * @link    http://binarybonsai.com/code/timesince.txt 
 * @license unknown - original source unavailable
 * 
 * @todo check human_time_diff(); as a replacement 
 * @link http://codex.wordpress.org/Function_Reference/human_time_diff
 * Note: Rarst said there\'s caching involved with this fn.
 * 
 * @param   (integer) $older_date
 * @param   (integer) $newer_date
 */
function get_time_since( $older_date, $newer_date = false )
{
    // array of time period chunks
    $chunks = array(
         array( 60 * 60 * 24 * 365 , \'year\' )
        ,array( 60 * 60 * 24 * 30 , \'month\' )
        ,array( 60 * 60 * 24 * 7, \'week\' )
        ,array( 60 * 60 * 24 , \'day\' )
        ,array( 60 * 60 , \'hour\' )
        ,array( 60 , \'min\' )
    );

    // $newer_date will equal false if we want to know the time elapsed between a date and the current time
    // $newer_date will have a value if we want to work out time elapsed between two known dates
    if ( $newer_date == false )
    {
        $newer_date = time() + ( 60 * 60 * get_option( \'gmt_offset\' ) );
    }
    else 
    {
        $newer_date = $newer_date;
    }

    // difference in seconds
    $since = $newer_date - $older_date;

    // we only want to output two chunks of time here, eg:
    // x years, xx months
    // x days, xx hours
    // so there\'s only two bits of calculation below:

    // step one: the first chunk
    for ( $i = 0, $j = count( $chunks ); $i < $j; $i++ )
    {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];

        // finding the biggest chunk (if the chunk fits, break)
        if ( ( $count = floor( $since / $seconds ) ) != 0 )
        {
            break;
        }
    }

    // set output var
    if ( $count == true )
    { 
        $output = "1 {$name2}";
    }
    else 
    {
        $output = "{$count} {$name}s";
    }

    // step two: the second chunk
    if ( $i + 1 < $j )
    {
        $seconds2 = $chunks[$i + 1][0];
        $name2 = $chunks[$i + 1][1];

        if ( ( $count2 = floor( ( $since - ( $seconds * $count ) ) / $seconds2 ) ) != 0 )
        {
            // add to output var
            if ( $count2 == true )
            {
                $output .= ", 1 {$name2}";
            }
            else 
            {
                $output .= ", {$count} {$name2}s";
            }
        }
    }

    return $output;
}

SO网友:Joshua Abenazer

在循环中尝试此代码。

<?php echo \'posted\' . human_time_diff( get_the_time(\'U\'), current_time( \'timestamp\' ) ) . \' ago\'; ?>

结束

相关推荐

Integrating plugins in themes

我找不到讨论这个的帖子,所以开始这篇。我目前正在为3.1+开发一个相当复杂的主题,我的意思是,除了样式和常规的前端功能之外,我还在主题的核心包括后端和前端的插件。因此,为了使这一点更有条理,我将其分为三个问题:集成插件是一种常见的做法吗</自动更新主题/插件有什么影响/复杂之处</在不破坏现有功能的情况下,包含每个插件的最佳方式是什么