我有一段代码,它显示了两个自定义字段之间的天数差异
<div class="distance">
<?php
$date1 = get_field( \'date_start\', false, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( \'Y-m-d\' ) );
$date2 = get_field( \'date_dun\', false, false );
$date2 = new DateTime( $date2 );
$unix2 = strtotime( $date2->format( \'Y-m-d\' ) );
if( 0 === ( $unix1 - $unix2 ) ) {
echo \'0\';
} elseif( $unix2 < $unix1 ) {
$days = ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
echo \'-\' . $days;
} else {
$days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
echo $days;
}
?>
</div>
我想做的是,当一篇文章被保存时,我使用wordpress提供的save\\u post操作,将上面输出的值添加为“difference”自定义字段的值,如下所示
function set_date_difference($post_id){
$countdays = (the output of the above code)
update_post_meta($post_id,\'difference\', $countdays);
}
add_action(\'save_post_event\',\'set_date_difference\');
最合适的回答,由SO网友:Johansson 整理而成
既然您已经提到您正在使用这些代码,我想它们都适用于您。现在,我为您将它们组合成一个函数,在发布帖子后更新元数据:
function set_date_difference($post_id){
// Get the value of the first field
$date1 = get_field(\'date_start\', $post_id, false );
$date1 = new DateTime( $date1 );
$unix1 = strtotime( $date1->format( \'Y-m-d\' ) );
// Get the value of the second field
$date2 = get_field( \'date_dun\', $post_id, false );
$date2 = new DateTime( $date2 );
$unix2 = strtotime( $date2->format( \'Y-m-d\' ) );
// Calculate the difference
if( 0 === ( $unix1 - $unix2 ) ) {
$days = 0;
} elseif( $unix2 < $unix1 ) {
$days = -1 * ( intval( $unix1 - $unix2 ) / DAY_IN_SECONDS );
} else {
$days = ( intval( $unix2 - $unix1 ) / DAY_IN_SECONDS );
}
// Update the field
update_post_meta($post_id,\'difference\', $days);
}
add_action(\'save_post\',\'set_date_difference\');
The
save_post
操作将帖子的ID传递给函数,以便您可以使用它来获取和更新字段。