Created
July 10, 2020 05:38
ACF preview update
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
add_filter( 'get_post_metadata', 'get_preview_post_meta_data', 10, 4 ); | |
add_action( 'wp_insert_post', 'save_preview_post' ); | |
add_action( 'save_preview_postmeta', 'acf_save_preview_postmeta' ); | |
function get_preview_post_meta_data( $meta_value, $post_id, $meta_key, $single ) { | |
global $post; | |
if ( ! empty( $_GET['preview'] ) && $post->ID == $post_id ) { | |
$preview = wp_get_post_autosave( $post_id ); | |
if ( $preview ) { | |
if ( $post_id != $preview->ID ) { | |
$meta_value = get_post_meta( $preview->ID, $meta_key, $single ); | |
} | |
} | |
} | |
return $meta_value; | |
} | |
/** | |
* プレビュー時にメタデータも保存するためのフックを実行する | |
* | |
* @param $post_id | |
*/ | |
function save_preview_post( $post_id ) { | |
if ( wp_is_post_revision( $post_id ) ) { | |
do_action( 'save_preview_postmeta', $post_id ); | |
} | |
} | |
/** | |
* プレビュー時にACFのメタデータも保存する | |
* | |
* @param $post_id | |
*/ | |
function acf_save_preview_postmeta( $post_id ) { | |
if ( ! function_exists( 'get_field_object' ) ) { | |
return; | |
} | |
if ( isset( $_POST['acf'] ) && is_array( $_POST['acf'] ) ) { | |
foreach ( $_POST['acf'] as $key => $value ) { | |
$field = get_field_object( $key ); | |
if ( empty( $field['name'] ) || empty( $field['key'] ) ) { | |
continue; | |
} | |
update_metadata( 'post', $post_id, $field['name'], $value ); | |
update_metadata( 'post', $post_id, "_" . $field['name'], $field['key'] ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment