Support

Account

Home Forums General Issues custom post type ui with acf field with unique value

Solving

custom post type ui with acf field with unique value

  • hi

    i want to create a custom post type that have a field (acf) with unique value
    for example student number (name: sn)

    please help me

    regards

  • If you are looking to have a field that only allows unique values across all posts see this comment https://support.advancedcustomfields.com/forums/topic/accept-only-unique-values/#post-45359

  • hi
    i have a custom post type “professor” and a relationship field ( refer to “person” custom post type ) with name of “persona” but this code did not work

    
    
    add_filter('acf/validate_value/name=persona', 'require_unique', 10, 4);
    function require_unique($valid, $value, $field, $input) {
      if (!$valid) {
        return $valid;
      }
      // get the post id
      // using field key of post id field
     
      // query existing posts for matching value
      $args = array(
        'post_type' => 'professor',
        'posts_per_page' => 1, // only need to see if there is 1
    
        'meta_query' => array(
          array(
            'key' => 'persona',
            'value' => $value
          )
        )
      );
      $query = new WP_Query($args);
      if (count($query->posts)){
        $valid = 'This Value is not Unique';
      }
    
      return $valid;
    }
    
  • Relationship fields to not work like standard field. Relationship field store a serialized array of values. You are basically trying to create a 1 to 1 relationship but the relationship field is a 1 to many relationship.

    First I would suggest switching to a post object field, which by default is a 1:1 relationship.

    If you can’t do that then I’d suggest reading this https://www.advancedcustomfields.com/resources/querying-relationship-fields/

  • i used post object field but even this simple code that i put in function.php is not working
    and posts are published

    
    add_filter('acf/validate_value/name=persona', 'require_unique', 10, 4);
    function require_unique($valid, $value, $field, $input) {
      if (!$valid) {
        return $valid;
      }
    
        $valid = 'This Value is not Unique';
      
    
      return $valid;
    }
    
  • Is the field “persona” a sub field of some kind?

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

You must be logged in to reply to this topic.