WordPress:强制重新发布帖子更新内容



我目前正在使用ACF自定义帖子类型。基本上,您填写一个表单,提交后,它会创建一个新的帖子,然后通过地图中的短代码可以看到详细信息。每个提交使用它自己的短代码,在它自己的弹出,出现在地图上(即[shortcode post_id=1])

我遇到的问题是,在提交时,短代码无法获取我刚刚提交的数据。当我在后端检查帖子时,所有字段都已填写。如果我按下后端上的更新按钮,数据将正常显示在短代码中。有什么方法可以自动使它工作吗?

我已经尝试了一些事情,例如在ACF上启用REST API,添加额外的save_post操作来尝试重新保存和更新内容。

下面是当前脚本处理我的保存:

// create saving post function
function my_acf_save_interactive_map_post( $post_id ) {
// exit based on certain conditions
if( get_post_type($post_id) !== 'interactive_map' ) {   
return;
}
if( is_admin() ) {   
return;   
}
// get post variables
$post = get_post($post_id);
// set post category
$category = $_POST['category'];
$category_id = get_term_by('slug', $category, 'interactive_map_category')->term_id;
wp_set_post_terms($post_id, $category_id, 'interactive_map_category', true);

// get map values
$map_key = get_field_key('geek_im_map');
$map_values = $_POST['acf'][$map_key];
$map_values_array = json_decode(str_replace('\', '', $map_values), true);
if(!empty($map_values_array)) {
// create longitude and latitude variables from map
$longitude = $map_values_array['lng'];
$latitude = $map_values_array['lat'];
// update longitude and latitude values
update_post_meta($post_id, 'geek_im_geolocation_geek_im_longitude', $longitude);
update_post_meta($post_id, 'geek_im_geolocation_geek_im_latitude', $latitude);
}
error_log(print_r($post, true));
// update post information
$title = ucwords($map_values_array['address']) . '(' . $post_id . ')';
update_post_meta($post_id, 'geek_im_info_geek_im_title', $title);
$content = '<div>[geek_interactive_map_display post_id="' . $post_id . '"]</div>';
update_post_meta($post_id, 'geek_im_info_geek_im_content', $content);
// custom function found in acf-submission-handler.php
post_custom_data($post_id, $category, $_POST);
}
// add action for saving post
add_action('acf/pre_save_post', 'my_acf_save_interactive_map_post', 5, 1);

然后是一个额外的函数来尝试再次更新帖子。

// create update post function
function my_acf_update_interactive_map_content( $post_id ) {
// exit based on certain conditions
if( get_post_type($post_id) !== 'interactive_map' ) {   
return;
}
if( is_admin() ) {   
return;   
}
// get post variables
$post = get_post($post_id);
// force post update
remove_action( 'save_post', 'my_acf_update_interactive_map_content');
wp_update_post(array("ID" => $post_id));
add_action( 'save_post', 'my_acf_update_interactive_map_content');
}
// add action for updating post
add_action('save_post', 'my_acf_update_interactive_map_content');

我已经尝试了各种不同的方法,但似乎不能找出为什么它不能正确地抓取数据。当我检查后端时,它已经全部存储在post页面上,但是只有当我手动按下"Update"时才会收集值。按钮。我只是想让它立即更新它已经拥有的数据。如有任何帮助,不胜感激。

正如@CBroe在我的帖子评论中指出的那样,解决方案是将update_post_meta替换为update_field,这是一个ACF函数。除此之外,使用字段键而不是字段名进行更新往往更好。或者,如果您正在使用组(像我一样),您可以将字段名更新为组名。

例如,如果您有一个名为"field"还有一个叫"群"的群体。您可以通过更新"group_field"来定位该字段。

最新更新