Skip to content

Instantly share code, notes, and snippets.

@jyokyoku
Created July 10, 2020 05:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jyokyoku/0343ce9b784766504bd15a5f6ce9af60 to your computer and use it in GitHub Desktop.
Save jyokyoku/0343ce9b784766504bd15a5f6ce9af60 to your computer and use it in GitHub Desktop.
ACF preview update
<?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