当您创建/更新特定于“要约”的帖子类型的帖子时,我正在尝试创建/更新帖子元。但是,它不会更新post meta。这段代码已添加到我的functions.php文件中。
add_filter( 'pre_post_update', 'update_voucher_deadline', 10, 2 );
function update_voucher_deadline( $post_id, $data ) {
$evergreen = get_field('offer_evergreen', $post_id);
if ($evergreen == "evergreen-yes") {
$year = date('Y');
$month = date('m');
$currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
$day = date("t", strtotime($currentDate));
$endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";
//global $post; Tried with this uncommented and also didn't work.
if ( ! add_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth)) {
update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
}
}
}
答案 0 :(得分:1)
我看到您使用ACF插件创建自定义字段,这意味着您可以使用acf/save_post
过滤器执行此操作。
1.检查我们是否保存帖子类型“优惠”
2.检查我们是否具有值为'evergreen-yes'的自定义字段'offer_evergreen'
3.检查是否已自定义提交“ offer_voucher_deadline”-更新他。
4.如果我们没有自定义字段“ offer_voucher_deadline”,请创建他并保存
我们的数据。
add_filter('acf/save_post', 'update_voucher_deadline', 20);
function update_voucher_deadline($post_id) {
if ( get_post_type($post_id) != 'offer' ) //if current post type not equal 'offer' return
return;
$year = date('Y');
$month = date('m');
$currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
$day = date("t", strtotime($currentDate));
$endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";
if ( get_field('offer_evergreen') == 'evergreen-yes' ) {
if ( get_post_meta( $post_id, 'offer_voucher_deadline', true ) ) //If get post meta with key 'offer_voucher_deadline' - update meta
update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
else //else if do not have post meta with key 'offer_voucher_deadline' create post meta
add_post_meta( $post_id, 'offer_voucher_deadline', $endOfMonth);
} else {
return; //Remove return and add what you want to save, if offer_evergreen not equal to evergreen-yes
}
}
答案 1 :(得分:0)
首先,pre_post_update
挂钩不会在创建时触发,而是会在现有帖子更新之前立即触发。
您需要使用save_post
钩子,它会在创建或更新帖子或页面时触发
add_action( 'save_post', 'update_voucher_deadline', 10, 3 );
/**
* Save post metadata when a post is saved.
*
* @param int $post_id The post ID.
* @param post $post The post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
function update_voucher_deadline( $post_id, $post, $update ) {
$evergreen = get_field('offer_evergreen');
if ($evergreen == "evergreen-yes") {
$year = date('Y');
$month = date('m');
$currentDate = "". $year . "-" . $month . "-" . date('d') . date('H') . ":" . date('i') . ":" . date('s');
$day = date("t", strtotime($currentDate));
$endOfMonth = "". $year . "-" . $month . "-" . $day . "23:59:00";
//global $post; Tried with this uncommented and also didn't work.
if ( ! add_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth)) {
update_post_meta($post_id, 'offer_voucher_deadline', $endOfMonth);
}
}
}
注意:您可以根据需要使用$update
参数来更新功能。