/*
Theme Name: GeneratePress Simple Child
Theme URI: https://generatepress.com/
Description: A clean, minimal child theme for adding your own website CSS and customizations.
Author: Website Owner
Template: generatepress
Version: 1.0.0
Text Domain: generatepress-simple-child
*/

/*
 * Add your custom CSS below.
 * Example:
 * body {
 *     background-color: #ffffff;
 * }
 */

/* =====================================
   CUSTOM SEO META KEYWORDS
===================================== */

// Add Meta Keywords box to Posts and Pages
add_action('add_meta_boxes', function () {

    foreach (['post', 'page'] as $screen) {

        add_meta_box(
            'custom_seo_keywords',
            'SEO Meta Keywords',
            function ($post) {

                $keywords = get_post_meta(
                    $post->ID,
                    '_custom_seo_keywords',
                    true
                );

                wp_nonce_field(
                    'custom_seo_save',
                    'custom_seo_nonce'
                );

                echo '<input type="text"
                    name="custom_seo_keywords"
                    value="' . esc_attr($keywords) . '"
                    placeholder="keyword 1, keyword 2, keyword 3"
                    style="width:100%;padding:10px;">';

                echo '<p>Enter keywords separated by commas.</p>';
            },
            $screen,
            'normal',
            'high'
        );
    }
});

// Save keywords
add_action('save_post', function ($post_id) {

    if (!isset($_POST['custom_seo_nonce'])) {
        return;
    }

    if (!wp_verify_nonce(
        sanitize_text_field(wp_unslash($_POST['custom_seo_nonce'])),
        'custom_seo_save'
    )) {
        return;
    }

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    if (wp_is_post_revision($post_id)) {
        return;
    }

    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    if (!in_array(get_post_type($post_id), ['post', 'page'], true)) {
        return;
    }

    $keywords = isset($_POST['custom_seo_keywords'])
        ? sanitize_text_field(wp_unslash($_POST['custom_seo_keywords']))
        : '';

    update_post_meta(
        $post_id,
        '_custom_seo_keywords',
        $keywords
    );
});

// Display keywords in HTML Head
add_action('wp_head', function () {

    if (!is_singular(['post', 'page'])) {
        return;
    }

    $keywords = get_post_meta(
        get_queried_object_id(),
        '_custom_seo_keywords',
        true
    );

    if ($keywords !== '') {
        echo '<meta name="keywords" content="' .
            esc_attr($keywords) . '">' . "\n";
    }

}, 99);
