Support

Account

Home Forums Bug Reports global $post it's returning null/empty value in "add_filter('acf/validate_value/

Helping

global $post it's returning null/empty value in "add_filter('acf/validate_value/

  • I want to validate duplicated posts and working well on creating new posts but when editing posts then its detecting the same post itself as duplicate. Apparently this behavoir is due to global $post it’s always returning null/empty value son cannot exclude the current post from the query.

    Some idea how to fix this please?

    add_filter('acf/validate_value/name=dni_de_paciente', 
                'validate_dni_de_paciente_filter', 10, 4);
    add_filter('acf/validate_value/name=cita_dni_paciente', 
                'validate_dni_de_paciente_filter', 10, 4);
    function validate_dni_de_paciente_filter($valid, $value, $field, $input) {
          if ( !$valid || $value == '') {
            return $valid;
          }
    
          global $post; 
    
          $args = array(
            'post_type' => 'paciente',  // or your post
            'post__not_in' => array($post->ID), // do not check this post
            'meta_query' => array(
              array(
                'key' => 'dni_de_paciente',
                'value' => $value,
                'compare' => '=',
              )
            )
          );
          $query = new WP_Query($args);
          if (count($query->posts)) {
            // found at least one post that
            // already has $value
            $valid = 'This post already exist! <a href="/wp-admin/edit.php?s='.$value.'&post_status=all&post_type=paciente">VER</a>';
          }
          return $valid;
    }
  • the global $post is not set during validation because validation is done with AJAX.

    You will find the post ID in $_POST[‘post_ID’]

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.