<?php //(functions.php)

/* 記事単位でカスタムCSS/JSを追記できるようにする
-------------------------------------- */
//メタボックス登録
add_action('add_meta_boxes', function () {
    foreach (['post', 'page'] as $post_type) {
        add_meta_box('custom_css', 'Custom CSS', 'render_custom_css_meta_box', $post_type, 'normal', 'high');
        add_meta_box('custom_js', 'Custom JS', 'render_custom_js_meta_box', $post_type, 'normal', 'high');
    }
});

function render_custom_css_meta_box($post) {
    wp_nonce_field('custom_css_nonce_action', 'custom_css_nonce');
    $value = get_post_meta($post->ID, '_custom_css', true);
    echo '<textarea name="custom_css" rows="5" style="width:100%;">' . esc_textarea($value) . '</textarea>';
}

function render_custom_js_meta_box($post) {
    wp_nonce_field('custom_js_nonce_action', 'custom_js_nonce');
    $value = get_post_meta($post->ID, '_custom_js', true);
    echo '<textarea name="custom_js" rows="5" style="width:100%;">' . esc_textarea($value) . '</textarea>';
}

//保存処理
add_action('save_post', function ($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    if (!current_user_can('edit_post', $post_id)) return;

    //CSS
    if (isset($_POST['custom_css_nonce']) && wp_verify_nonce($_POST['custom_css_nonce'], 'custom_css_nonce_action')) {
        $css = isset($_POST['custom_css']) ? wp_strip_all_tags($_POST['custom_css']) : '';
        update_post_meta($post_id, '_custom_css', $css);
    }

    //JS
    if (isset($_POST['custom_js_nonce']) && wp_verify_nonce($_POST['custom_js_nonce'], 'custom_js_nonce_action')) {
        $js = isset($_POST['custom_js']) ? $_POST['custom_js'] : '';
        update_post_meta($post_id, '_custom_js', $js);
    }
});

//フロント出力
add_action('wp_head', function () {
    if (!is_singular()) return;
    $post_id = get_queried_object_id();

    $css = get_post_meta($post_id, '_custom_css', true);
    if ($css) {
        echo '<style>' . wp_strip_all_tags($css) . '</style>';
    }

    $js = get_post_meta($post_id, '_custom_js', true);
    if ($js) {
        echo '<script>' . $js . '</script>';
    }
});