下面的代码在我插入帖子/提交表单时使用add\\u post\\u meta时有效。页面刷新完美无瑕(请参阅How can I fix a slow redirect after form submit from frontend (no plugin)?). 然而,当使用我打算使用update\\u post\\u meta为我的自定义帖子类型更新帖子meta的表单时,我似乎无法获得相同的效果。
function wpd_check_submission(){
if( isset( $_POST[\'start\'] ) ) {
// do your post insertion here
}
}
add_action( \'init\', \'wpd_check_submission\' );
有人能帮我指出正确的方向吗?我找不到一个明确的答案。我尝试使用save\\u post挂钩,将if-isset行直接放在我的表单之后,将update\\u post\\u元函数直接添加到正在工作的函数中。我已经开始阅读关于更新post meta的do\\u操作方法,这些方法已经更新了\\u post\\u meta和update\\u post\\u meta--我真的很困惑。
下面是一个示例:有效的代码:
function ty_save_post_data() {
if( isset( $_POST[\'start\'] ) ) {
$post = array(
\'post_title\' => $_POST[ \'mfname\' ],
\'post_status\' => \'publish\',
\'post_type\' => \'add-members\'
);
$post_id = wp_insert_post($post);
add_post_meta($post_id, \'mfname\', sanitize_text_field( $_POST[ \'mfname\' ] ), true);
add_post_meta($post_id, \'mem\', sanitize_text_field( $_POST[ \'mem\' ] ), true);
add_post_meta($post_id, \'mpw\', esc_attr( $_POST[\'mpw\'] ), true);
add_post_meta($post_id, \'second-nom\', sanitize_text_field( $_POST[ \'second-nom\' ] ), true );
}
}
add_action( \'init\', \'ty_save_post_data\' );
失败的代码:
function ty_save_post_data1() {
if( isset( $_POST[\'isecond\'] ) ) {
update_post_meta( get_the_ID(), \'second-nom\', sanitize_text_field( $_POST[\'second-nom\'] ) );
update_post_meta( get_the_ID(), \'second-nom-date\', sanitize_text_field( $_POST[\'second-nom-date\'] ) );
update_post_meta( get_the_ID(), \'approved\', sanitize_text_field( $_POST[\'approved\'] ) );
}
}
add_action( \'init\', \'ty_save_post_data1\' );
HERE IS THE UPDATED WORKING VERSION OF THE FAILED CODE EXAMPLE
//hidden field added to form that grabs the post ID
<input type="hidden" name="post_id" id="post_id" value="<?php echo get_the_ID(); ?>" />
<?php function ty_save_post_data1() {
if( isset( $_POST[\'isecond\'] ) ) {
$post_id1 = $_POST[\'post_id\'];
update_post_meta( $post_id1, \'second-nom\', sanitize_text_field( $_POST[\'second-nom\'] ) );
update_post_meta( $post_id1, \'second-nom-date\', sanitize_text_field( $_POST[\'second-nom-date\'] ) );
update_post_meta( $post_id1, \'approved\', sanitize_text_field( $_POST[\'approved\'] ) );
}
}
add_action( \'init\', \'ty_save_post_data1\' );
?>