Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.9 kB
2
Indexable
        function prevent_trash_and_display_values($post_id) {
            // Get the post title
            $currentPostTitle = get_the_title($post_id);
            // Get ACF field values
            $default = get_field('default', $post_id);
            $post_id = get_the_ID(); // Get the current post ID

            if ($default === true){
                // $currentPostTitle = get_the_title(); // Get the title of the current post
                return filterPlansWithDefault2($currentPostTitle); // Call the function with the current post title

            } elseif ($default === false) {
                // delete post
            }         
        }
        add_action('wp_trash_post', 'prevent_trash_and_display_values');
        

        function filterPlansWithDefault2($currentTitle) {
            // Define the query arguments to retrieve all 'plans' posts with 'default' value equal to 1
            
            $args = array(
                'post_type' => 'plans',
                'posts_per_page' => -1, // Retrieve all posts
                'meta_query' => array(
                    array(
                        'key' => 'default',
                        'value' => 1,
                        'compare' => '=',
                    ),
                ),
            );
           

            // Create a new WP_Query instance with the defined arguments
            $query = new WP_Query($args);


            if ($query->have_posts()) {
                while ($query->have_posts()) {
                    $query->the_post();

                    $postTitle = get_the_title();
                    $default = get_field('default', $post_id);
                    $status = get_post_status_object(get_post_status($post_id))->label;

                    // if there are 2 default
                    if ($postTitle === $currentTitle || $status === 'Draft') {
                        // delete post
                    } else {
                        // if there is only one Default

                        display_alert_trash($post_id);

                        // Restore the post to its original status
                        wp_untrash_post($post_id);

                        // Prevent further execution
                        exit;         
                    }
                }
                wp_reset_postdata(); // Reset the query
            }
            
            error_log('filterPlansWithDefault_avoidTrashDefault executed.');
        }

        function display_alert_trash($post_id)
        {
            echo '<script type="text/javascript">
                    var message = "This post is the only Default for this provider, can\'t be deleted";
                    alert(message);
                    window.location.href="/wp-admin/edit.php?post_type=plans"
                
                </script>';
        }