Support

Account

Home Forums ACF PRO Checking ACF Field Value Is Unique

Helping

Checking ACF Field Value Is Unique

  • Hi all,

    I’ve been trawling the forums trying to find a solution for this.

    We have an ACF field group called Additional Course Data group_5edb89be3792c which contains several fields including course_code.

    This is assigned to Learndash Courses post type.

    Each course requires a course_code which must be unique.

    I’m trying to create a function that will reside in my child theme functions.php – that checks to see if the code is unique whenever a user clones or creates a new course and then checks the course_code is unique when they try to publish, and if it’s not unique, then display a warning “Course Code must be unique” so that the course_code is edited before publishing.

    I’m not the greatest PHP developer in the world, so I’ve tried using codewp.ai to give me the basics, but I just can’t get it to work.

    Any pointers would be greatly appreciated.I’ve been trawling the forums trying to find a solution for this.

    This is where I’m at, but can’t get this to work

    // Check that course code is unique
    
    function cwpai_check_course_code_unique() {
        global $post;
        if (get_post_type($post) == 'sfwd-courses') {
            $course_code = get_field('course_code', $post->ID);
            $args = array(
                'post_type' => 'sfwd-courses',
                'post_status' => 'publish',
                'meta_query' => array(
                    array(
                        'key' => 'course_code',
                        'value' => $course_code,
                        'compare' => '='
                    )
                )
            );
            $query = new WP_Query($args);
            if ($query->have_posts()) {
                $query->the_post();
                if ($post->ID != $post->ID) {
                    $url = admin_url('post.php?post=' . $post->ID . '&action=edit');
                    $message = sprintf(__('The course code %s is already in use by %s. Please choose a unique course code.', 'cwpai'), $course_code, '<a href="' . $url . '">' . get_the_title() . '</a>');
                    ?>
                    <div class="error">
                        <p><?php echo $message; ?></p>
                    </div>
                    <?php
                }
            }
        }
    }
    add_action('admin_notices', 'cwpai_check_course_code_unique');
    
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.