来自其他字段的Wordpress自定义字段值(如果为空)


Wordpress Custom Field value from an other field (if is empty)

我有两个自定义字段:"开始日期"answers"结束日期"。

如果管理员没有设置"结束日期"字段,我想动态设置结束日期和开始日期。

有可能吗?

我对我的字段使用ACF,但如果必要,我可以在php中导出我的字段:以添加到文件functions.php

我使用元密钥进行查询。

起初,我使用"开始日期"来对我的活动进行排序。但当一个活动在几天内举行时,它会在第二天之后取消。

因此,现在我使用"结束日期",但一天中的事件没有定义"终止日期"。

作为参考,如果我在一天内为我的活动定义了一个"结束日期":它有效。但我会简化事件的发布,如果事件是一天,则不需要设置结束日期(因为它与开始日期相同)

我的代码:

$args = array(
  'post_type'=>'evenement','meta_key'=>'end-date','orderby'=>'meta_value_num' , 'order'=>'ASC' , 'posts_per_page'=> 3,

'meta_query'=> array (array('key' => 'end-date', 'compare' => '>=', 'value' => $current_date, 'type' => 'numeric',))

); query_posts( $args );

I speak very little English sorry if I'm not understandable

Maybe the problem can be solved if the fields are filled at the time of publication of the post. Is it possible to set the default value of the "end-date" field with the "start-date" fields

I've found your question, because I have exactly the same problem as you. My answer comes two years later, but maybe it could help someone that is having the same issue.

The way to get it is to use an ACF filter executed while saving the custom field value.

// Auto-populate end date if it is empty.
function update_end_date_cf( $value, $post_id, $field ) {
   //NOTE: don't use get_field() because it retrieves the value
   //in a preformatted way different as it is saved in database       
   $end_date = get_post_meta( $post_id, 'end_date_cf_name', true );
   $start_date = get_post_meta( $post_id, 'start_date_cf_name', true );
   if ($end_date == '' && $start_date != '') {
      $value = $start_date;
   }
   return $value;
}
add_filter('acf/update_value/name=end_date_cf_name', 'update_end_date_cf', 10, 3);

希望它能有所帮助!

逻辑:

if end-date is empty
set end-date equal to start-date

它看起来像这个

<?php if( get_field('end-date') ): ?>
    <?php $end-date = $start-date ?>    
     //Your code here                
<?php endif; ?>