<?php

/**
 * Conditional display of ACF field based on the current URL.
 */
function cwpai_conditional_acf_field_display($field) {
    // Get the current URL
    $current_url = $_SERVER['REQUEST_URI'];

    // Check if the URL is for the 'Add New Tag' screen or the tag listing page
    if (strpos($current_url, '/wp-admin/edit-tags.php?taxonomy=post_tag') !== false) {
        // Further check if it's not an individual tag edit screen
        if (strpos($current_url, '&tag_ID=') === false) {
            // If we are on the 'Add New Tag' or tag listing page, return false to hide the field
            return false;
        }
    }

    // If conditions are not met, show the field normally
    return $field;
}
add_filter('acf/prepare_field/key=field_1', 'cwpai_conditional_acf_field_display');

/**
 * Use ACF to create a custom field in the tag edit form for selecting posts.
 * (No changes needed here, provided for context)
 */
function cwpai_add_acf_to_tags() {
    if(function_exists('acf_add_local_field_group')):
        acf_add_local_field_group(array(
            'key' => 'group_1',
            'title' => 'Post Selector',
            'fields' => array(
                array(
                    'key' => 'field_1',
                    'label' => 'Select Posts',
                    'name' => 'select_posts',
                    'type' => 'post_object',
                    'post_type' => array('post'),
                    'multiple' => 1,
                    'return_format' => 'id',
                ),
            ),
            'location' => array(
                array(
                    array(
                        'param' => 'taxonomy',
                        'operator' => '==',
                        'value' => 'post_tag',
                    ),
                ),
            ),
        ));
    endif;
}
add_action('acf/init', 'cwpai_add_acf_to_tags');

/**
 * Save selected posts to the tag when the tag is edited.
 * (No changes needed here, provided for context)
 */
function cwpai_save_tag($term_id) {
    if (isset($_POST['acf'])) {
        $selected_posts = $_POST['acf']['field_1']; // Ensure this matches the actual field key used in $_POST data

        if (!empty($selected_posts)) {
            foreach ($selected_posts as $post_id) {
                wp_set_post_terms($post_id, array($term_id), 'post_tag', true);
            }
        }
    }
}
add_action('edited_term', 'cwpai_save_tag');