WordPress 在编辑帖子页面保存,更新帖子元



当您创建/更新专门针对"报价"类型的帖子时,我正在尝试创建/更新帖子元。但是,它不会更新帖子元。此代码已添加到我的函数.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);
}
}
}

我看到您使用 ACF 插件创建自定义字段acf/save_post这意味着您可以使用过滤器来执行此操作。
1. 检查我们是否保存了帖子类型"报价">
2。检查我们是否有值为"evergreen-yes"3 的自定义字段"offer_evergreen
"。如果是,请检查我们是否有自定义提交的"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
}
}

首先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您可以使用参数更新函数。

最新更新