WordPress

[WordPress]ACFカスタムフィールドプレビュー

公開済みの記事を編集してプレビューするとカスタムフィールドの値が古いままなのを解決する
※公式対応までのつなぎ
※2024/12/27 最新版ACFProに合わせて修正

 
functions.phpに下記追記

/**
 * $dataをjsonで出力
 */
function echo_json($data)
{
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode($data);
}
/**
 * テンプレートのadmin.jsを読み込む
 */
function add_admin_style()
{
    $path_js = get_template_directory_uri().'/scripts/admin.js';
    wp_enqueue_script('admin_script', $path_js);
}
add_action('admin_enqueue_scripts', 'add_admin_style');
/**
 * ajaxで送信されたカスタムフィールドの値をdbへ保存
 */
function save_acf_by_ajax()
{
    if(empty($_POST['post_id'])){
        echo_json(['success' => false,'preview_id' => 0]);
        wp_die();
        exit;
    }
    $post_id = $_POST['post_id'];
    $post_status = get_post_status($post_id);
    if($post_status !== "publish"){
        echo_json(['success' => false,'preview_id' => 0]);
        wp_die();
        exit;
    }
    $preview_id = 0;
    global $wpdb;
    $row = $wpdb->get_row("SELECT p.ID FROM $wpdb->posts AS p WHERE p.post_type = '_cf_preview_id' AND p.post_parent = ${post_id} ORDER BY p.ID DESC LIMIT 1");
    if(empty($row)) {
        $post = array(
            'post_name'      => '_cf_preview_id',
            'post_title'     => '_cf_preview_id',
            'post_status'    => 'private',
            'post_type'      => '_cf_preview_id',
            'post_author'    => 1,
            'ping_status'    => 'closed',
            'post_parent'    => $post_id,
            'comment_status' => 'closed',
        );
        $preview_id = wp_insert_post($post);
    }else{
        $preview_id = $row->ID;
    }
    unset($_POST['action']);
    unset($_POST['post_id']);
    unset($_POST['preview_id']);
    if(!empty($preview_id)) {
        foreach ($_POST as $key => $value) {
            update_field($key, $value, $preview_id);
        }
    }
    $_POST['post_id'] = $post_id;
    $_POST['preview_id'] = $preview_id;
    $_POST['success'] = !empty($preview_id);
    echo_json($_POST);
    wp_die();
}
add_action( 'wp_ajax_save_acf_by_ajax_action', 'save_acf_by_ajax' );
/**
 * プレビュー時カスタムフィールドの値用のpostidを返す
 */
function get_cf_post_id($post_id = '')
{
    if(empty($post_id)){
        $post_id = get_the_ID();
    }
    $cf_post_id = $post_id;
    if(is_preview()){
        $post_status = get_post_status($post_id);
        if($post_status === 'publish'){
            global $wpdb;
            $row = $wpdb->get_row("SELECT p.ID FROM $wpdb->posts AS p WHERE p.post_type = '_cf_preview_id' AND p.post_parent = ${post_id}");
            if (!empty($row)) {
                $cf_post_id = $row->ID;
            }
        }
    }
    return $cf_post_id;
}

wp-content/themes/テーマ/assets/js/admin.jsに下記追記

class CFSaveManager {
    qsall(selector,elm){
        if(!elm)elm = document;
        return elm.querySelectorAll(selector);
    }
    qs(selector,elm){
        if(!elm)elm = document;
        return elm.querySelector(selector);
    }
    constructor(){
    }
    /* 初期化 */
    init(){
        this.initAutoSave();
    }
    /* プレビューボタンにイベント設定 */
    initAutoSave(){
        const button = this.qs('.editor-preview-dropdown__toggle.components-dropdown-menu__toggle');
        if(!button){
            setTimeout(() => {
                this.initAutoSave();
            },200);
            return;
        }
        button.addEventListener('click',() => {
            this.autoSave();
        });
    }
    /* ajaxでカスタムフィールドの値をapiへ送信・保存 */
    autoSave(){
        const elm = this.qs('[name="post_ID"]');
        const form = this.qs('form.metabox-location-normal');
        const formData = new FormData(form);
        let sendFormData = new FormData();
        for (let item of formData) {
            if(/^acf\[.+\]$/.test(item[0])){
                const key = item[0].split('[').pop().replace(/\]$/,'');
                if(key){
                    sendFormData.append(key,item[1]);
                }
            }else{
                sendFormData.append(item[0],item[1]);
            }
        }
        sendFormData.append('action','save_acf_by_ajax_action');
        sendFormData.append('post_id',elm.value);
        const options = {
            method  : "POST",
            headers : {
                'Accept': 'application/json'
            },
            body    : sendFormData
        };
        fetch(window.ajaxurl,options)
            .then((response)=>{
                if (!response.ok) {
                    throw new Error();
                }
                return response.json();
            })
            .then((json)=>{
                console.log(json);
            })
            .catch(console.error);
    }
}
window.addEventListener('DOMContentLoaded',(e) => {
    const cfsm = new CFSaveManager();
    cfsm.init();
});

wpテンプレでカスタムフィールドの値を出力する部分

$post_id = get_the_ID();
if(is_preview()){
    $post_id = get_cf_post_id($post_id);
}
$value = get_field( "test_text1" ,$post_id);
echo "post_id :$post_id <br>";
echo "<h2>test_text1:".esc_html($value)."</h2>";

[WordPress]MW WP Formの問い合わせデータ表示順指定カスタムフィールド追加

functions.phpに下記を追記

// カスタムフィールドボックス[問い合わせデータの表示順]
function add_mw_order_fields() {
    //add_meta_box(表示される入力ボックスのHTMLのID, ラベル, 表示する内容を作成する関数名, 投稿タイプ, 表示方法)
    add_meta_box( 'mw_order_setting', '問い合わせデータの表示順', 'insert_mw_order_fields', 'mw-wp-form', 'normal');
}
add_action('admin_menu', 'add_mw_order_fields');
// カスタムフィールドの入力エリア[問い合わせデータの表示順]
function insert_mw_order_fields() {
    global $post;
    echo '<div><input style="width: 100%;" type="text" name="mw_order" value="'.get_post_meta($post->ID, 'mw_order', true).'" size="50" placeholder=""/></div>';
}
// カスタムフィールドの値を保存[問い合わせデータの表示順]
function save_mw_order_fields( $post_id ) {
    if(!empty($_POST['mw_order'])){
        update_post_meta($post_id, 'mw_order', $_POST['mw_order'] );
    }else{
        delete_post_meta($post_id, 'mw_order');
    }
}
add_action('save_post', 'save_mw_order_fields');
// カスタムフィールドの値による問い合わせデータ表示順設定
function my_mwform_inquiry_data_columns( $columns ) {
    if(empty($_GET['post_type']) || strpos($_GET['post_type'],'mwf_') === false){
        return $columns;
    }
    $tmp = explode('_',$_GET['post_type']);
    if(count($tmp) < 2 || !is_numeric($tmp[1])) {
        return $columns;
    }
    $meta = get_post_meta($tmp[1],'mw_order',true);
    if (empty($meta)) {
        return $columns;
    }
    $order = explode(',',$meta);
    $result = [];
    foreach ($order as $key => $value){
        if(empty($value))continue;
        $result[$value] = $value;
    }
    return $result;
}
// フィルターフックの要否を判定し必要なら処理を設定する
if(!empty($_GET['post_type']) && strpos($_GET['post_type'],'mwf_') === 0){
    $tmp = explode('_',$_GET['post_type']);
    if(1 < count($tmp) && is_numeric($tmp[1])) {
        $meta = get_post_meta($tmp[1], 'mw_order',true);
        if (!empty($meta)) {
            add_filter('mwform_inquiry_data_columns-mwf_' . $tmp[1], 'my_mwform_inquiry_data_columns');
        }
    }
}

 
追加されたカスタムフィールドへnameをカンマ区切りで入力する。

[WordPress]アップロード画像の複数サイズ自動生成停止

下記実行

update wp_options set option_value='0' where option_name = 'thumbnail_size_w';
update wp_options set option_value='0' where option_name = 'thumbnail_size_h';
update wp_options set option_value='0' where option_name = 'medium_size_w';
update wp_options set option_value='0' where option_name = 'medium_size_h';
update wp_options set option_value='0' where option_name = 'large_size_w';
update wp_options set option_value='0' where option_name = 'large_size_h';
update wp_options set option_value='0' where option_name = 'medium_large_size_w';
update wp_options set option_value='0' where option_name = 'medium_large_size_h';

 
functions.phpに下記追加

function disable_image_sizes( $new_sizes ) {
    unset( $new_sizes['1536x1536'] );
    unset( $new_sizes['2048x2048'] );
    unset( $new_sizes['post-thumbnail'] );
    unset( $new_sizes['category-thumb'] );
    unset( $new_sizes['homepage-thumb'] );
    return $new_sizes;
}
add_filter( 'intermediate_image_sizes_advanced', 'disable_image_sizes' );

add_filter( 'big_image_size_threshold', '__return_false' );

[WordPress]get_post_by_post_name

public function get_post_by_post_name($post_name, $post_type = '', $post_status = 'publish')
{
    global $wpdb;
    $sql = array();
    $sql[] = "SELECT p.*";
    $sql[] = "FROM $wpdb->posts AS p";
    $sql[] = "WHERE p.post_name " . $this->__get_sql_for_in($post_name);
    if (!empty($post_type))
        $sql[] = "AND p.post_type = '$post_type'";
    if(!empty($post_status))
        $sql[] = "AND p.post_status = '$post_status'";
    $result = $wpdb->get_results(implode(' ', $sql));
    if (empty($result))
        return null;
    return is_array($post_name) ? $result : $result[0];
}
protected function __get_sql_for_in($values, $is_number = false)
{
    $quote    = $is_number ? "" : "'";
    $is_array = is_array($values);
    $not      = ($is_array && is_string($values[0]) && preg_match('/^.*\!=.+$/',$values[0])) || (!$is_array && is_string($values) && preg_match('/^.*\!=.+$/',$values));
    $in       = $not ? ' NOT IN' : ' IN';
    $eq       = $not ? '!=' : '=';
    if($is_array){
        foreach ($values as $i => $value) {
            $values[$i] = preg_replace('/^(\!=|=)/', '', esc_sql($value));
            $values[$i] = preg_replace('/^ /', '', esc_sql($value));
        }
    }else{
        $values = preg_replace('/^(\!=|=)/','',esc_sql($values));
        $values = preg_replace('/^ /','',esc_sql($values));
    }
    return $is_array && 1 < count($values) ? "{$in} ({$quote}" . implode("{$quote},{$quote}", $values) . "{$quote})" : ($is_array ? "{$eq} {$quote}{$values[0]}{$quote}" : "{$eq} {$quote}$values{$quote}");
}

[WordPress]wp_head不要タグ削除

remove_action( 'wp_head', 'wp_resource_hints', 2 );
remove_action( 'wp_head', 'rest_output_link_wp_head', 10, 0 );
remove_action( 'wp_head', 'feed_links_extra', 3);
remove_action( 'wp_head', 'wp_generator');
remove_action( 'wp_head', 'rsd_link' );
remove_action( 'wp_head', 'wlwmanifest_link' );
remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
remove_action( 'wp_head', 'wp_print_styles', 8 );

[WordPress]メニュー削除

function remove_noneed_menus()
{
    global $menu;
    global $submenu;

    unset($menu[5]);  // 投稿
    //unset($menu[20]);  // 固定ページ
    unset($menu[25]);  // コメント
}
add_action('admin_menu', 'remove_noneed_menus');

[WordPress]テンプレ切替

function add_user_rewrite_rules()
{
    add_rewrite_rule("^post_type1/?$", "index.php?post_type=post_type1&mode=archive", 'top');
    add_rewrite_rule("^post_type1/article/([^\/]+)/?$", 'index.php?post_type=post_type1&name=$matches[1]&mode=single', 'top');
    add_rewrite_rule("^post_type2/?$", "index.php?post_type=post_type2&mode=archive", 'top');
    add_rewrite_rule("^post_type2/(\d+)/?$", 'index.php?post_type=post_type2&p=$matches[1]&mode=single', 'top');
}
add_action('init', 'add_user_rewrite_rules');

function add_user_routes_query_vars($query_vars)
{
    $query_vars[] = 'mode';
    $query_vars[] = 'param';
    return $query_vars;
}
add_filter('query_vars', 'add_user_routes_query_vars');

/**
 * is_single,is_archiveの返値が確定する前に処理
 * @param $query
 */
function my_parse_request($query)
{
    if(is_admin())
        return;
    
    if($query->query_vars['post_type'] === 'post_type1') {
        $query->query_vars['posts_per_page'] = 10;
    }else if($query->query_vars['post_type'] === 'post_type2') {
        $query->query_vars['posts_per_page'] = 20;
    }else if($query->query_vars['post_type'] === 'post_type3'){
    }
}
add_action( 'parse_request', 'my_parse_request');

function my_pre_get_posts( $query )
{
    if ( is_admin() || ! $query->is_main_query() ){
        return;
    }
    if($query->query['post_type'] === 'post_type1') {
        if (!empty($_GET['api'])) {
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }
    }else if($query->query['post_type'] === 'post_type2') {
        if (!empty($_GET['api'])) {
            if (isset($_GET['cate'])) {
                $tax_query[] = array(
                    'taxonomy' => 'tax_type',
                    'terms'    => array($_GET['cate']),
                    'field'    => 'slug',
                    'operator' => 'IN');
                $query->set('tax_query', array('relation' => 'OR', $tax_query));
            }
            if(!empty($_GET['count']) && preg_match('/^\d+$/',$_GET['count'])){
                $query->set('posts_per_page',$_GET['count']);
            }else{
                $query->set('posts_per_page',3);
            }
        }else if (isset($query->query['param'])) {
            $tax_query[] = array(
                'taxonomy' => 'tax_type',
                'terms'    => array($query->query['param']),
                'field'    => 'slug',
                'operator' => 'IN');
            $query->set('tax_query', array('relation' => 'OR', $tax_query));
        }
    }
}
add_action('pre_get_posts','my_pre_get_posts');

/**
 * テンプレートファイル切替
 * @param $template
 * @return mixed
 */
function my_template_include($template)
{
    global $wp_query;
    if($wp_query->query['post_type'] === 'post_type1' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top') {
        $bn = basename($template);
        return preg_replace("/{$bn}$/","index-post_type1.php",$template);
        
    }else if($wp_query->query['post_type'] === 'post_type2' && isset($wp_query->query['mode']) && $wp_query->query['mode'] === 'top'){
        $bn = basename($template);
        return preg_replace("/{$bn}$/","archive-post_type2.php",$template);

    }else if($wp_query->query['post_type'] === 'post_type3'){
        if($wp_query->query['mode'] === 'single'){
            $bn = basename($template);
            return preg_replace("/{$bn}$/","single-post_type3.php",$template);
        }
    }
    return $template;
}
add_filter('template_include','my_template_include');


[WordPress]wp_enqueue_script

function my_original_option()
{
    add_menu_page('オリジナルメニュー','オリジナルメニュー','manage_options','my_option','my_option','',30);
}
add_action('admin_menu', 'my_original_option');

function my_option()
{
    include TEMPLATEPATH . DIRECTORY_SEPARATOR . 'my_option.php';
}
function my_register_scripts()
{
    if(is_admin() && !empty($_GET['page']) && $_GET['page']==='my_option') {
        $keyname = 'my_option';
        $result = wp_register_script($keyname, get_template_directory_uri() . '/scripts/admin-custom.js', array('jquery', 'jquery-ui-sortable'));
        wp_enqueue_script($keyname);
    }
}
add_action('init', 'my_register_scripts');

[WordPress]ACF Pro Wysiwyg用関数

public function is_empty_wysiwyg_content($content)
{
    $content = $this->get_string_from_wysiwyg_content($content);
    return $content === '';
}
public function get_wysiwyg_content($content)
{
    return apply_filters('acf_the_content',$content);
}
public function get_string_from_wysiwyg_content($_content)
{
    $is_empty = trim(preg_replace('/<[^>]+?>/','',$_content)) == ' ';
    if($is_empty)
        return '';
    return trim(html_entity_decode(preg_replace('/<[^>]+?>/','',$_content)));
}